blob: 40ff9b4eac42b9b71580fc48e838b84eea12faed [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
LoopDawg592860c2016-06-09 08:57:35 -06002//Copyright (C) 2014-2016 LunarG, Inc.
John Kessenich6c292d32016-02-15 20:58:50 -07003//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060050}
John Kessenich140f3df2015-06-26 16:58:36 -060051
52// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020053#include "../glslang/MachineIndependent/localintermediate.h"
54#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060055#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050056#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060057
John Kessenich140f3df2015-06-26 16:58:36 -060058#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040060#include <list>
61#include <map>
62#include <stack>
63#include <string>
64#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060065
66namespace {
67
John Kessenich55e7d112015-11-15 21:33:39 -070068// For low-order part of the generator's magic number. Bump up
69// when there is a change in the style (e.g., if SSA form changes,
70// or a different instruction sequence to do something gets used).
71const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060072
qining4c912612016-04-01 10:35:16 -040073namespace {
74class SpecConstantOpModeGuard {
75public:
76 SpecConstantOpModeGuard(spv::Builder* builder)
77 : builder_(builder) {
78 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040079 }
80 ~SpecConstantOpModeGuard() {
81 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
82 : builder_->setToNormalCodeGenMode();
83 }
qining40887662016-04-03 22:20:42 -040084 void turnOnSpecConstantOpMode() {
85 builder_->setToSpecConstCodeGenMode();
86 }
qining4c912612016-04-01 10:35:16 -040087
88private:
89 spv::Builder* builder_;
90 bool previous_flag_;
91};
92}
93
John Kessenich140f3df2015-06-26 16:58:36 -060094//
95// The main holder of information for translating glslang to SPIR-V.
96//
97// Derives from the AST walking base class.
98//
99class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
100public:
Lei Zhang17535f72016-05-04 15:55:59 -0400101 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenich140f3df2015-06-26 16:58:36 -0600102 virtual ~TGlslangToSpvTraverser();
103
104 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
105 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
106 void visitConstantUnion(glslang::TIntermConstantUnion*);
107 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
108 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
109 void visitSymbol(glslang::TIntermSymbol* symbol);
110 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
111 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
112 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
113
John Kessenich7ba63412015-12-20 17:37:07 -0700114 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600115
116protected:
Rex Xubbceed72016-05-21 09:40:44 +0800117 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100118 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700119 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600120 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
121 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600122 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
123 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
124 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600125 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700126 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600127 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
128 glslang::TLayoutPacking, const glslang::TQualifier&);
129 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
130 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700131 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700132 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800133 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600134 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700135 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700136 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
137 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
138 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100139 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600140
John Kessenich6fccb3c2016-09-19 16:01:41 -0600141 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600142 void makeFunctions(const glslang::TIntermSequence&);
143 void makeGlobalInitializers(const glslang::TIntermSequence&);
144 void visitFunctions(const glslang::TIntermSequence&);
145 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800146 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600147 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
148 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600149 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
150
qining25262b32016-05-06 17:25:16 -0400151 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);
152 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
153 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 +0800154 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 +0800155 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600156 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800157 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 +0800158 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xub7072052016-09-26 15:53:40 +0800159 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600160 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 +0800161 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600162 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
163 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700164 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600165 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700166 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400167 spv::Id createSpvConstant(const glslang::TIntermTyped&);
168 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600169 bool isTrivialLeaf(const glslang::TIntermTyped* node);
170 bool isTrivial(const glslang::TIntermTyped* node);
171 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800172 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600173
174 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700175 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600176 int sequenceDepth;
177
Lei Zhang17535f72016-05-04 15:55:59 -0400178 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400179
John Kessenich140f3df2015-06-26 16:58:36 -0600180 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
181 spv::Builder builder;
182 bool inMain;
183 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700184 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 -0700185 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600186 const glslang::TIntermediate* glslangIntermediate;
187 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800188 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600189
John Kessenich2f273362015-07-18 22:34:27 -0600190 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600191 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600192 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700193 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600194 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600195 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600196};
197
198//
199// Helper functions for translating glslang representations to SPIR-V enumerants.
200//
201
202// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700203spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600204{
John Kessenich66e2faf2016-03-12 18:34:36 -0700205 switch (source) {
206 case glslang::EShSourceGlsl:
207 switch (profile) {
208 case ENoProfile:
209 case ECoreProfile:
210 case ECompatibilityProfile:
211 return spv::SourceLanguageGLSL;
212 case EEsProfile:
213 return spv::SourceLanguageESSL;
214 default:
215 return spv::SourceLanguageUnknown;
216 }
217 case glslang::EShSourceHlsl:
Dan Baker55d5f2d2016-08-15 16:05:45 -0400218 //Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
219 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600220 default:
221 return spv::SourceLanguageUnknown;
222 }
223}
224
225// Translate glslang language (stage) to SPIR-V execution model.
226spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
227{
228 switch (stage) {
229 case EShLangVertex: return spv::ExecutionModelVertex;
230 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
231 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
232 case EShLangGeometry: return spv::ExecutionModelGeometry;
233 case EShLangFragment: return spv::ExecutionModelFragment;
234 case EShLangCompute: return spv::ExecutionModelGLCompute;
235 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700236 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600237 return spv::ExecutionModelFragment;
238 }
239}
240
241// Translate glslang type to SPIR-V storage class.
242spv::StorageClass TranslateStorageClass(const glslang::TType& type)
243{
244 if (type.getQualifier().isPipeInput())
245 return spv::StorageClassInput;
246 else if (type.getQualifier().isPipeOutput())
247 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700248 else if (type.getBasicType() == glslang::EbtSampler)
249 return spv::StorageClassUniformConstant;
250 else if (type.getBasicType() == glslang::EbtAtomicUint)
251 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600252 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700253 if (type.getQualifier().layoutPushConstant)
254 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600255 if (type.getBasicType() == glslang::EbtBlock)
256 return spv::StorageClassUniform;
257 else
258 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600259 // TODO: how are we distinguishing between default and non-default non-writable uniforms? Do default uniforms even exist?
John Kessenich140f3df2015-06-26 16:58:36 -0600260 } else {
261 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700262 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
263 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600264 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
265 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400266 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700267 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600268 return spv::StorageClassFunction;
269 }
270 }
271}
272
273// 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.
308spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
309{
310 if (type.getBasicType() == glslang::EbtBlock) {
311 switch (type.getQualifier().storage) {
312 case glslang::EvqUniform: return spv::DecorationBlock;
313 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
314 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 Xubbceed72016-05-21 09:40:44 +0800383spv::Decoration 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
393 else if (qualifier.explicitInterp)
394 return spv::DecorationExplicitInterpAMD;
395#endif
Rex Xubbceed72016-05-21 09:40:44 +0800396 else
John Kessenich4016e382016-07-15 11:53:56 -0600397 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800398}
399
400// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600401// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800402// should be applied.
403spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
404{
405 if (qualifier.patch)
406 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700407 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600408 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700409 else if (qualifier.sample) {
410 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600411 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700412 } else
John Kessenich4016e382016-07-15 11:53:56 -0600413 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600414}
415
John Kessenich92187592016-02-01 13:45:25 -0700416// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700417spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600418{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700419 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600420 return spv::DecorationInvariant;
421 else
John Kessenich4016e382016-07-15 11:53:56 -0600422 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600423}
424
qining9220dbb2016-05-04 17:34:38 -0400425// If glslang type is noContraction, return SPIR-V NoContraction decoration.
426spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
427{
428 if (qualifier.noContraction)
429 return spv::DecorationNoContraction;
430 else
John Kessenich4016e382016-07-15 11:53:56 -0600431 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400432}
433
David Netoa901ffe2016-06-08 14:11:40 +0100434// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
435// associated capabilities when required. For some built-in variables, a capability
436// is generated only when using the variable in an executable instruction, but not when
437// just declaring a struct member variable with it. This is true for PointSize,
438// ClipDistance, and CullDistance.
439spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600440{
441 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700442 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600443 // Defer adding the capability until the built-in is actually used.
444 if (! memberDeclaration) {
445 switch (glslangIntermediate->getStage()) {
446 case EShLangGeometry:
447 builder.addCapability(spv::CapabilityGeometryPointSize);
448 break;
449 case EShLangTessControl:
450 case EShLangTessEvaluation:
451 builder.addCapability(spv::CapabilityTessellationPointSize);
452 break;
453 default:
454 break;
455 }
John Kessenich92187592016-02-01 13:45:25 -0700456 }
457 return spv::BuiltInPointSize;
458
John Kessenichebb50532016-05-16 19:22:05 -0600459 // These *Distance capabilities logically belong here, but if the member is declared and
460 // then never used, consumers of SPIR-V prefer the capability not be declared.
461 // They are now generated when used, rather than here when declared.
462 // Potentially, the specification should be more clear what the minimum
463 // use needed is to trigger the capability.
464 //
John Kessenich92187592016-02-01 13:45:25 -0700465 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100466 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600467 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700468 return spv::BuiltInClipDistance;
469
470 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100471 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600472 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700473 return spv::BuiltInCullDistance;
474
475 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500476 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700477 return spv::BuiltInViewportIndex;
478
John Kessenich5e801132016-02-15 11:09:46 -0700479 case glslang::EbvSampleId:
480 builder.addCapability(spv::CapabilitySampleRateShading);
481 return spv::BuiltInSampleId;
482
483 case glslang::EbvSamplePosition:
484 builder.addCapability(spv::CapabilitySampleRateShading);
485 return spv::BuiltInSamplePosition;
486
487 case glslang::EbvSampleMask:
488 builder.addCapability(spv::CapabilitySampleRateShading);
489 return spv::BuiltInSampleMask;
490
John Kessenich78a45572016-07-08 14:05:15 -0600491 case glslang::EbvLayer:
492 builder.addCapability(spv::CapabilityGeometry);
493 return spv::BuiltInLayer;
494
John Kessenich140f3df2015-06-26 16:58:36 -0600495 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600496 case glslang::EbvVertexId: return spv::BuiltInVertexId;
497 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700498 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
499 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600500 case glslang::EbvBaseVertex:
501 case glslang::EbvBaseInstance:
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200502
John Kessenichda581a22015-10-14 14:10:30 -0600503 case glslang::EbvDrawId:
504 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600505 logger->missingFunctionality("shader draw parameters");
John Kessenich4016e382016-07-15 11:53:56 -0600506 return spv::BuiltInMax;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200507
508 case glslang::EbvPrimitiveId:
509 if (glslangIntermediate->getStage() == EShLangFragment)
510 builder.addCapability(spv::CapabilityGeometry);
511 return spv::BuiltInPrimitiveId;
512
John Kessenich140f3df2015-06-26 16:58:36 -0600513 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600514 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
515 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
516 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
517 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
518 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
519 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
520 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600521 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
522 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
523 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
524 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
525 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
526 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
527 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
528 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800529
Rex Xu574ab042016-04-14 16:53:07 +0800530 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800531 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800532 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
533 return spv::BuiltInSubgroupSize;
534
Rex Xu574ab042016-04-14 16:53:07 +0800535 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800536 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800537 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
538 return spv::BuiltInSubgroupLocalInvocationId;
539
Rex Xu574ab042016-04-14 16:53:07 +0800540 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800541 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
542 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
543 return spv::BuiltInSubgroupEqMaskKHR;
544
Rex Xu574ab042016-04-14 16:53:07 +0800545 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800546 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
547 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
548 return spv::BuiltInSubgroupGeMaskKHR;
549
Rex Xu574ab042016-04-14 16:53:07 +0800550 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800551 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
552 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
553 return spv::BuiltInSubgroupGtMaskKHR;
554
Rex Xu574ab042016-04-14 16:53:07 +0800555 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800556 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
557 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
558 return spv::BuiltInSubgroupLeMaskKHR;
559
Rex Xu574ab042016-04-14 16:53:07 +0800560 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800561 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
562 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
563 return spv::BuiltInSubgroupLtMaskKHR;
564
Rex Xu9d93a232016-05-05 12:30:44 +0800565#ifdef AMD_EXTENSIONS
566 case glslang::EbvBaryCoordNoPersp: return spv::BuiltInBaryCoordNoPerspAMD;
567 case glslang::EbvBaryCoordNoPerspCentroid: return spv::BuiltInBaryCoordNoPerspCentroidAMD;
568 case glslang::EbvBaryCoordNoPerspSample: return spv::BuiltInBaryCoordNoPerspSampleAMD;
569 case glslang::EbvBaryCoordSmooth: return spv::BuiltInBaryCoordSmoothAMD;
570 case glslang::EbvBaryCoordSmoothCentroid: return spv::BuiltInBaryCoordSmoothCentroidAMD;
571 case glslang::EbvBaryCoordSmoothSample: return spv::BuiltInBaryCoordSmoothSampleAMD;
572 case glslang::EbvBaryCoordPullModel: return spv::BuiltInBaryCoordPullModelAMD;
573#endif
John Kessenich4016e382016-07-15 11:53:56 -0600574 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600575 }
576}
577
Rex Xufc618912015-09-09 16:42:49 +0800578// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700579spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800580{
581 assert(type.getBasicType() == glslang::EbtSampler);
582
John Kessenich5d0fa972016-02-15 11:57:00 -0700583 // Check for capabilities
584 switch (type.getQualifier().layoutFormat) {
585 case glslang::ElfRg32f:
586 case glslang::ElfRg16f:
587 case glslang::ElfR11fG11fB10f:
588 case glslang::ElfR16f:
589 case glslang::ElfRgba16:
590 case glslang::ElfRgb10A2:
591 case glslang::ElfRg16:
592 case glslang::ElfRg8:
593 case glslang::ElfR16:
594 case glslang::ElfR8:
595 case glslang::ElfRgba16Snorm:
596 case glslang::ElfRg16Snorm:
597 case glslang::ElfRg8Snorm:
598 case glslang::ElfR16Snorm:
599 case glslang::ElfR8Snorm:
600
601 case glslang::ElfRg32i:
602 case glslang::ElfRg16i:
603 case glslang::ElfRg8i:
604 case glslang::ElfR16i:
605 case glslang::ElfR8i:
606
607 case glslang::ElfRgb10a2ui:
608 case glslang::ElfRg32ui:
609 case glslang::ElfRg16ui:
610 case glslang::ElfRg8ui:
611 case glslang::ElfR16ui:
612 case glslang::ElfR8ui:
613 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
614 break;
615
616 default:
617 break;
618 }
619
620 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800621 switch (type.getQualifier().layoutFormat) {
622 case glslang::ElfNone: return spv::ImageFormatUnknown;
623 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
624 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
625 case glslang::ElfR32f: return spv::ImageFormatR32f;
626 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
627 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
628 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
629 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
630 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
631 case glslang::ElfR16f: return spv::ImageFormatR16f;
632 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
633 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
634 case glslang::ElfRg16: return spv::ImageFormatRg16;
635 case glslang::ElfRg8: return spv::ImageFormatRg8;
636 case glslang::ElfR16: return spv::ImageFormatR16;
637 case glslang::ElfR8: return spv::ImageFormatR8;
638 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
639 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
640 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
641 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
642 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
643 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
644 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
645 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
646 case glslang::ElfR32i: return spv::ImageFormatR32i;
647 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
648 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
649 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
650 case glslang::ElfR16i: return spv::ImageFormatR16i;
651 case glslang::ElfR8i: return spv::ImageFormatR8i;
652 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
653 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
654 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
655 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
656 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
657 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
658 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
659 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
660 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
661 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600662 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800663 }
664}
665
qining25262b32016-05-06 17:25:16 -0400666// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700667// descriptor set.
668bool IsDescriptorResource(const glslang::TType& type)
669{
John Kessenichf7497e22016-03-08 21:36:22 -0700670 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700671 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700672 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700673
674 // non block...
675 // basically samplerXXX/subpass/sampler/texture are all included
676 // if they are the global-scope-class, not the function parameter
677 // (or local, if they ever exist) class.
678 if (type.getBasicType() == glslang::EbtSampler)
679 return type.getQualifier().isUniformOrBuffer();
680
681 // None of the above.
682 return false;
683}
684
John Kesseniche0b6cad2015-12-24 10:30:13 -0700685void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
686{
687 if (child.layoutMatrix == glslang::ElmNone)
688 child.layoutMatrix = parent.layoutMatrix;
689
690 if (parent.invariant)
691 child.invariant = true;
692 if (parent.nopersp)
693 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800694#ifdef AMD_EXTENSIONS
695 if (parent.explicitInterp)
696 child.explicitInterp = true;
697#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700698 if (parent.flat)
699 child.flat = true;
700 if (parent.centroid)
701 child.centroid = true;
702 if (parent.patch)
703 child.patch = true;
704 if (parent.sample)
705 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800706 if (parent.coherent)
707 child.coherent = true;
708 if (parent.volatil)
709 child.volatil = true;
710 if (parent.restrict)
711 child.restrict = true;
712 if (parent.readonly)
713 child.readonly = true;
714 if (parent.writeonly)
715 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700716}
717
John Kessenichf2b7f332016-09-01 17:05:23 -0600718bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700719{
John Kessenich7b9fa252016-01-21 18:56:57 -0700720 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600721 // - struct members might inherit from a struct declaration
722 // (note that non-block structs don't explicitly inherit,
723 // only implicitly, meaning no decoration involved)
724 // - affect decorations on the struct members
725 // (note smooth does not, and expecting something like volatile
726 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700727 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600728 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700729}
730
John Kessenich140f3df2015-06-26 16:58:36 -0600731//
732// Implement the TGlslangToSpvTraverser class.
733//
734
Lei Zhang17535f72016-05-04 15:55:59 -0400735TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
736 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
737 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600738 inMain(false), mainTerminated(false), linkageOnly(false),
739 glslangIntermediate(glslangIntermediate)
740{
741 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
742
743 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700744 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600745 stdBuiltins = builder.import("GLSL.std.450");
746 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600747 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
748 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600749
750 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600751 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
752 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600753 builder.addSourceExtension(it->c_str());
754
755 // Add the top-level modes for this shader.
756
John Kessenich92187592016-02-01 13:45:25 -0700757 if (glslangIntermediate->getXfbMode()) {
758 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600759 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700760 }
John Kessenich140f3df2015-06-26 16:58:36 -0600761
762 unsigned int mode;
763 switch (glslangIntermediate->getStage()) {
764 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600765 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600766 break;
767
768 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600769 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600770 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
771 break;
772
773 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600774 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600775 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700776 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
777 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
778 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600779 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600780 }
John Kessenich4016e382016-07-15 11:53:56 -0600781 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600782 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
783
John Kesseniche6903322015-10-13 16:29:02 -0600784 switch (glslangIntermediate->getVertexSpacing()) {
785 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
786 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
787 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600788 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600789 }
John Kessenich4016e382016-07-15 11:53:56 -0600790 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600791 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
792
793 switch (glslangIntermediate->getVertexOrder()) {
794 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
795 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600796 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600797 }
John Kessenich4016e382016-07-15 11:53:56 -0600798 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600799 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
800
801 if (glslangIntermediate->getPointMode())
802 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600803 break;
804
805 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600806 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600807 switch (glslangIntermediate->getInputPrimitive()) {
808 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
809 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
810 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700811 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600812 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600813 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600814 }
John Kessenich4016e382016-07-15 11:53:56 -0600815 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600816 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600817
John Kessenich140f3df2015-06-26 16:58:36 -0600818 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
819
820 switch (glslangIntermediate->getOutputPrimitive()) {
821 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
822 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
823 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600824 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600825 }
John Kessenich4016e382016-07-15 11:53:56 -0600826 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600827 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
828 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
829 break;
830
831 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600832 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600833 if (glslangIntermediate->getPixelCenterInteger())
834 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600835
John Kessenich140f3df2015-06-26 16:58:36 -0600836 if (glslangIntermediate->getOriginUpperLeft())
837 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600838 else
839 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600840
841 if (glslangIntermediate->getEarlyFragmentTests())
842 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
843
844 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600845 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
846 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600847 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600848 }
John Kessenich4016e382016-07-15 11:53:56 -0600849 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600850 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
851
852 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
853 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600854 break;
855
856 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600857 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600858 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
859 glslangIntermediate->getLocalSize(1),
860 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600861 break;
862
863 default:
864 break;
865 }
866
867}
868
John Kessenich7ba63412015-12-20 17:37:07 -0700869// Finish everything and dump
870void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
871{
872 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100873 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
874 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700875
qiningda397332016-03-09 19:54:03 -0500876 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700877 builder.dump(out);
878}
879
John Kessenich140f3df2015-06-26 16:58:36 -0600880TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
881{
882 if (! mainTerminated) {
883 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
884 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600885 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600886 }
887}
888
889//
890// Implement the traversal functions.
891//
892// Return true from interior nodes to have the external traversal
893// continue on to children. Return false if children were
894// already processed.
895//
896
897//
qining25262b32016-05-06 17:25:16 -0400898// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600899// - uniform/input reads
900// - output writes
901// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
902// - something simple that degenerates into the last bullet
903//
904void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
905{
qining75d1d802016-04-06 14:42:01 -0400906 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
907 if (symbol->getType().getQualifier().isSpecConstant())
908 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
909
John Kessenich140f3df2015-06-26 16:58:36 -0600910 // getSymbolId() will set up all the IO decorations on the first call.
911 // Formal function parameters were mapped during makeFunctions().
912 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700913
914 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
915 if (builder.isPointer(id)) {
916 spv::StorageClass sc = builder.getStorageClass(id);
917 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
918 iOSet.insert(id);
919 }
920
921 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700922 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600923 // Prepare to generate code for the access
924
925 // L-value chains will be computed left to right. We're on the symbol now,
926 // which is the left-most part of the access chain, so now is "clear" time,
927 // followed by setting the base.
928 builder.clearAccessChain();
929
930 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700931 // except for
John Kessenich4bf71552016-09-02 11:20:21 -0600932 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -0700933 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -0600934 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -0700935 // These are also pure R-values.
936 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -0600937 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -0600938 builder.setAccessChainRValue(id);
939 else
940 builder.setAccessChainLValue(id);
941 }
942}
943
944bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
945{
qining40887662016-04-03 22:20:42 -0400946 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
947 if (node->getType().getQualifier().isSpecConstant())
948 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
949
John Kessenich140f3df2015-06-26 16:58:36 -0600950 // First, handle special cases
951 switch (node->getOp()) {
952 case glslang::EOpAssign:
953 case glslang::EOpAddAssign:
954 case glslang::EOpSubAssign:
955 case glslang::EOpMulAssign:
956 case glslang::EOpVectorTimesMatrixAssign:
957 case glslang::EOpVectorTimesScalarAssign:
958 case glslang::EOpMatrixTimesScalarAssign:
959 case glslang::EOpMatrixTimesMatrixAssign:
960 case glslang::EOpDivAssign:
961 case glslang::EOpModAssign:
962 case glslang::EOpAndAssign:
963 case glslang::EOpInclusiveOrAssign:
964 case glslang::EOpExclusiveOrAssign:
965 case glslang::EOpLeftShiftAssign:
966 case glslang::EOpRightShiftAssign:
967 // A bin-op assign "a += b" means the same thing as "a = a + b"
968 // where a is evaluated before b. For a simple assignment, GLSL
969 // says to evaluate the left before the right. So, always, left
970 // node then right node.
971 {
972 // get the left l-value, save it away
973 builder.clearAccessChain();
974 node->getLeft()->traverse(this);
975 spv::Builder::AccessChain lValue = builder.getAccessChain();
976
977 // evaluate the right
978 builder.clearAccessChain();
979 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700980 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600981
982 if (node->getOp() != glslang::EOpAssign) {
983 // the left is also an r-value
984 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700985 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600986
987 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -0600988 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -0400989 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600990 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
991 node->getType().getBasicType());
992
993 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700994 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600995 }
996
997 // store the result
998 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -0600999 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001000
1001 // assignments are expressions having an rValue after they are evaluated...
1002 builder.clearAccessChain();
1003 builder.setAccessChainRValue(rValue);
1004 }
1005 return false;
1006 case glslang::EOpIndexDirect:
1007 case glslang::EOpIndexDirectStruct:
1008 {
1009 // Get the left part of the access chain.
1010 node->getLeft()->traverse(this);
1011
1012 // Add the next element in the chain
1013
David Netoa901ffe2016-06-08 14:11:40 +01001014 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001015 if (! node->getLeft()->getType().isArray() &&
1016 node->getLeft()->getType().isVector() &&
1017 node->getOp() == glslang::EOpIndexDirect) {
1018 // This is essentially a hard-coded vector swizzle of size 1,
1019 // so short circuit the access-chain stuff with a swizzle.
1020 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001021 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001022 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001023 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001024 int spvIndex = glslangIndex;
1025 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1026 node->getOp() == glslang::EOpIndexDirectStruct)
1027 {
1028 // This may be, e.g., an anonymous block-member selection, which generally need
1029 // index remapping due to hidden members in anonymous blocks.
1030 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1031 assert(remapper.size() > 0);
1032 spvIndex = remapper[glslangIndex];
1033 }
John Kessenichebb50532016-05-16 19:22:05 -06001034
David Netoa901ffe2016-06-08 14:11:40 +01001035 // normal case for indexing array or structure or block
1036 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1037
1038 // Add capabilities here for accessing PointSize and clip/cull distance.
1039 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001040 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001041 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001042 }
1043 }
1044 return false;
1045 case glslang::EOpIndexIndirect:
1046 {
1047 // Structure or array or vector indirection.
1048 // Will use native SPIR-V access-chain for struct and array indirection;
1049 // matrices are arrays of vectors, so will also work for a matrix.
1050 // Will use the access chain's 'component' for variable index into a vector.
1051
1052 // This adapter is building access chains left to right.
1053 // Set up the access chain to the left.
1054 node->getLeft()->traverse(this);
1055
1056 // save it so that computing the right side doesn't trash it
1057 spv::Builder::AccessChain partial = builder.getAccessChain();
1058
1059 // compute the next index in the chain
1060 builder.clearAccessChain();
1061 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001062 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001063
1064 // restore the saved access chain
1065 builder.setAccessChain(partial);
1066
1067 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001068 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001069 else
John Kessenichfa668da2015-09-13 14:46:30 -06001070 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001071 }
1072 return false;
1073 case glslang::EOpVectorSwizzle:
1074 {
1075 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001076 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001077 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001078 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001079 }
1080 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001081 case glslang::EOpLogicalOr:
1082 case glslang::EOpLogicalAnd:
1083 {
1084
1085 // These may require short circuiting, but can sometimes be done as straight
1086 // binary operations. The right operand must be short circuited if it has
1087 // side effects, and should probably be if it is complex.
1088 if (isTrivial(node->getRight()->getAsTyped()))
1089 break; // handle below as a normal binary operation
1090 // otherwise, we need to do dynamic short circuiting on the right operand
1091 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1092 builder.clearAccessChain();
1093 builder.setAccessChainRValue(result);
1094 }
1095 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001096 default:
1097 break;
1098 }
1099
1100 // Assume generic binary op...
1101
John Kessenich32cfd492016-02-02 12:37:46 -07001102 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001103 builder.clearAccessChain();
1104 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001105 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001106
John Kessenich32cfd492016-02-02 12:37:46 -07001107 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001108 builder.clearAccessChain();
1109 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001110 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001111
John Kessenich32cfd492016-02-02 12:37:46 -07001112 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001113 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001114 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001115 convertGlslangToSpvType(node->getType()), left, right,
1116 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001117
John Kessenich50e57562015-12-21 21:21:11 -07001118 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001119 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001120 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001121 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001122 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001123 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001124 return false;
1125 }
John Kessenich140f3df2015-06-26 16:58:36 -06001126}
1127
1128bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1129{
qining40887662016-04-03 22:20:42 -04001130 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1131 if (node->getType().getQualifier().isSpecConstant())
1132 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1133
John Kessenichfc51d282015-08-19 13:34:18 -06001134 spv::Id result = spv::NoResult;
1135
1136 // try texturing first
1137 result = createImageTextureFunctionCall(node);
1138 if (result != spv::NoResult) {
1139 builder.clearAccessChain();
1140 builder.setAccessChainRValue(result);
1141
1142 return false; // done with this node
1143 }
1144
1145 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001146
1147 if (node->getOp() == glslang::EOpArrayLength) {
1148 // Quite special; won't want to evaluate the operand.
1149
1150 // Normal .length() would have been constant folded by the front-end.
1151 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001152 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001153 assert(node->getOperand()->getType().isRuntimeSizedArray());
1154 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1155 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001156 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1157 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001158
1159 builder.clearAccessChain();
1160 builder.setAccessChainRValue(length);
1161
1162 return false;
1163 }
1164
John Kessenichfc51d282015-08-19 13:34:18 -06001165 // Start by evaluating the operand
1166
John Kessenich8c8505c2016-07-26 12:50:38 -06001167 // Does it need a swizzle inversion? If so, evaluation is inverted;
1168 // operate first on the swizzle base, then apply the swizzle.
1169 spv::Id invertedType = spv::NoType;
1170 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1171 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1172 invertedType = getInvertedSwizzleType(*node->getOperand());
1173
John Kessenich140f3df2015-06-26 16:58:36 -06001174 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001175 if (invertedType != spv::NoType)
1176 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1177 else
1178 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001179
Rex Xufc618912015-09-09 16:42:49 +08001180 spv::Id operand = spv::NoResult;
1181
1182 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1183 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001184 node->getOp() == glslang::EOpAtomicCounter ||
1185 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001186 operand = builder.accessChainGetLValue(); // Special case l-value operands
1187 else
John Kessenich32cfd492016-02-02 12:37:46 -07001188 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001189
John Kessenichf6640762016-08-01 19:44:00 -06001190 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001191 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001192
1193 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001194 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001195 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001196
1197 // if not, then possibly an operation
1198 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001199 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001200
1201 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001202 if (invertedType)
1203 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1204
John Kessenich140f3df2015-06-26 16:58:36 -06001205 builder.clearAccessChain();
1206 builder.setAccessChainRValue(result);
1207
1208 return false; // done with this node
1209 }
1210
1211 // it must be a special case, check...
1212 switch (node->getOp()) {
1213 case glslang::EOpPostIncrement:
1214 case glslang::EOpPostDecrement:
1215 case glslang::EOpPreIncrement:
1216 case glslang::EOpPreDecrement:
1217 {
1218 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001219 spv::Id one = 0;
1220 if (node->getBasicType() == glslang::EbtFloat)
1221 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001222 else if (node->getBasicType() == glslang::EbtDouble)
1223 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001224#ifdef AMD_EXTENSIONS
1225 else if (node->getBasicType() == glslang::EbtFloat16)
1226 one = builder.makeFloat16Constant(1.0F);
1227#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001228 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1229 one = builder.makeInt64Constant(1);
1230 else
1231 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001232 glslang::TOperator op;
1233 if (node->getOp() == glslang::EOpPreIncrement ||
1234 node->getOp() == glslang::EOpPostIncrement)
1235 op = glslang::EOpAdd;
1236 else
1237 op = glslang::EOpSub;
1238
John Kessenichf6640762016-08-01 19:44:00 -06001239 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001240 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001241 convertGlslangToSpvType(node->getType()), operand, one,
1242 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001243 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001244
1245 // The result of operation is always stored, but conditionally the
1246 // consumed result. The consumed result is always an r-value.
1247 builder.accessChainStore(result);
1248 builder.clearAccessChain();
1249 if (node->getOp() == glslang::EOpPreIncrement ||
1250 node->getOp() == glslang::EOpPreDecrement)
1251 builder.setAccessChainRValue(result);
1252 else
1253 builder.setAccessChainRValue(operand);
1254 }
1255
1256 return false;
1257
1258 case glslang::EOpEmitStreamVertex:
1259 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1260 return false;
1261 case glslang::EOpEndStreamPrimitive:
1262 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1263 return false;
1264
1265 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001266 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001267 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001268 }
John Kessenich140f3df2015-06-26 16:58:36 -06001269}
1270
1271bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1272{
qining27e04a02016-04-14 16:40:20 -04001273 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1274 if (node->getType().getQualifier().isSpecConstant())
1275 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1276
John Kessenichfc51d282015-08-19 13:34:18 -06001277 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001278 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1279 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001280
1281 // try texturing
1282 result = createImageTextureFunctionCall(node);
1283 if (result != spv::NoResult) {
1284 builder.clearAccessChain();
1285 builder.setAccessChainRValue(result);
1286
1287 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001288 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001289 // "imageStore" is a special case, which has no result
1290 return false;
1291 }
John Kessenichfc51d282015-08-19 13:34:18 -06001292
John Kessenich140f3df2015-06-26 16:58:36 -06001293 glslang::TOperator binOp = glslang::EOpNull;
1294 bool reduceComparison = true;
1295 bool isMatrix = false;
1296 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001297 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001298
1299 assert(node->getOp());
1300
John Kessenichf6640762016-08-01 19:44:00 -06001301 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001302
1303 switch (node->getOp()) {
1304 case glslang::EOpSequence:
1305 {
1306 if (preVisit)
1307 ++sequenceDepth;
1308 else
1309 --sequenceDepth;
1310
1311 if (sequenceDepth == 1) {
1312 // If this is the parent node of all the functions, we want to see them
1313 // early, so all call points have actual SPIR-V functions to reference.
1314 // In all cases, still let the traverser visit the children for us.
1315 makeFunctions(node->getAsAggregate()->getSequence());
1316
John Kessenich6fccb3c2016-09-19 16:01:41 -06001317 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001318 // anything else gets there, so visit out of order, doing them all now.
1319 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1320
1321 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1322 // so do them manually.
1323 visitFunctions(node->getAsAggregate()->getSequence());
1324
1325 return false;
1326 }
1327
1328 return true;
1329 }
1330 case glslang::EOpLinkerObjects:
1331 {
1332 if (visit == glslang::EvPreVisit)
1333 linkageOnly = true;
1334 else
1335 linkageOnly = false;
1336
1337 return true;
1338 }
1339 case glslang::EOpComma:
1340 {
1341 // processing from left to right naturally leaves the right-most
1342 // lying around in the access chain
1343 glslang::TIntermSequence& glslangOperands = node->getSequence();
1344 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1345 glslangOperands[i]->traverse(this);
1346
1347 return false;
1348 }
1349 case glslang::EOpFunction:
1350 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001351 if (isShaderEntryPoint(node)) {
John Kessenich140f3df2015-06-26 16:58:36 -06001352 inMain = true;
1353 builder.setBuildPoint(shaderEntry->getLastBlock());
1354 } else {
1355 handleFunctionEntry(node);
1356 }
1357 } else {
1358 if (inMain)
1359 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001360 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001361 inMain = false;
1362 }
1363
1364 return true;
1365 case glslang::EOpParameters:
1366 // Parameters will have been consumed by EOpFunction processing, but not
1367 // the body, so we still visited the function node's children, making this
1368 // child redundant.
1369 return false;
1370 case glslang::EOpFunctionCall:
1371 {
1372 if (node->isUserDefined())
1373 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001374 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1375 if (result) {
1376 builder.clearAccessChain();
1377 builder.setAccessChainRValue(result);
1378 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001379 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001380
1381 return false;
1382 }
1383 case glslang::EOpConstructMat2x2:
1384 case glslang::EOpConstructMat2x3:
1385 case glslang::EOpConstructMat2x4:
1386 case glslang::EOpConstructMat3x2:
1387 case glslang::EOpConstructMat3x3:
1388 case glslang::EOpConstructMat3x4:
1389 case glslang::EOpConstructMat4x2:
1390 case glslang::EOpConstructMat4x3:
1391 case glslang::EOpConstructMat4x4:
1392 case glslang::EOpConstructDMat2x2:
1393 case glslang::EOpConstructDMat2x3:
1394 case glslang::EOpConstructDMat2x4:
1395 case glslang::EOpConstructDMat3x2:
1396 case glslang::EOpConstructDMat3x3:
1397 case glslang::EOpConstructDMat3x4:
1398 case glslang::EOpConstructDMat4x2:
1399 case glslang::EOpConstructDMat4x3:
1400 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001401#ifdef AMD_EXTENSIONS
1402 case glslang::EOpConstructF16Mat2x2:
1403 case glslang::EOpConstructF16Mat2x3:
1404 case glslang::EOpConstructF16Mat2x4:
1405 case glslang::EOpConstructF16Mat3x2:
1406 case glslang::EOpConstructF16Mat3x3:
1407 case glslang::EOpConstructF16Mat3x4:
1408 case glslang::EOpConstructF16Mat4x2:
1409 case glslang::EOpConstructF16Mat4x3:
1410 case glslang::EOpConstructF16Mat4x4:
1411#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001412 isMatrix = true;
1413 // fall through
1414 case glslang::EOpConstructFloat:
1415 case glslang::EOpConstructVec2:
1416 case glslang::EOpConstructVec3:
1417 case glslang::EOpConstructVec4:
1418 case glslang::EOpConstructDouble:
1419 case glslang::EOpConstructDVec2:
1420 case glslang::EOpConstructDVec3:
1421 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001422#ifdef AMD_EXTENSIONS
1423 case glslang::EOpConstructFloat16:
1424 case glslang::EOpConstructF16Vec2:
1425 case glslang::EOpConstructF16Vec3:
1426 case glslang::EOpConstructF16Vec4:
1427#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001428 case glslang::EOpConstructBool:
1429 case glslang::EOpConstructBVec2:
1430 case glslang::EOpConstructBVec3:
1431 case glslang::EOpConstructBVec4:
1432 case glslang::EOpConstructInt:
1433 case glslang::EOpConstructIVec2:
1434 case glslang::EOpConstructIVec3:
1435 case glslang::EOpConstructIVec4:
1436 case glslang::EOpConstructUint:
1437 case glslang::EOpConstructUVec2:
1438 case glslang::EOpConstructUVec3:
1439 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001440 case glslang::EOpConstructInt64:
1441 case glslang::EOpConstructI64Vec2:
1442 case glslang::EOpConstructI64Vec3:
1443 case glslang::EOpConstructI64Vec4:
1444 case glslang::EOpConstructUint64:
1445 case glslang::EOpConstructU64Vec2:
1446 case glslang::EOpConstructU64Vec3:
1447 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001448 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001449 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001450 {
1451 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001452 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001453 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001454 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001455 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001456 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001457 std::vector<spv::Id> constituents;
1458 for (int c = 0; c < (int)arguments.size(); ++c)
1459 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001460 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001461 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001462 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001463 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001464 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001465
1466 builder.clearAccessChain();
1467 builder.setAccessChainRValue(constructed);
1468
1469 return false;
1470 }
1471
1472 // These six are component-wise compares with component-wise results.
1473 // Forward on to createBinaryOperation(), requesting a vector result.
1474 case glslang::EOpLessThan:
1475 case glslang::EOpGreaterThan:
1476 case glslang::EOpLessThanEqual:
1477 case glslang::EOpGreaterThanEqual:
1478 case glslang::EOpVectorEqual:
1479 case glslang::EOpVectorNotEqual:
1480 {
1481 // Map the operation to a binary
1482 binOp = node->getOp();
1483 reduceComparison = false;
1484 switch (node->getOp()) {
1485 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1486 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1487 default: binOp = node->getOp(); break;
1488 }
1489
1490 break;
1491 }
1492 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001493 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001494 binOp = glslang::EOpMul;
1495 break;
1496 case glslang::EOpOuterProduct:
1497 // two vectors multiplied to make a matrix
1498 binOp = glslang::EOpOuterProduct;
1499 break;
1500 case glslang::EOpDot:
1501 {
qining25262b32016-05-06 17:25:16 -04001502 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001503 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001504 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001505 binOp = glslang::EOpMul;
1506 break;
1507 }
1508 case glslang::EOpMod:
1509 // when an aggregate, this is the floating-point mod built-in function,
1510 // which can be emitted by the one in createBinaryOperation()
1511 binOp = glslang::EOpMod;
1512 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001513 case glslang::EOpEmitVertex:
1514 case glslang::EOpEndPrimitive:
1515 case glslang::EOpBarrier:
1516 case glslang::EOpMemoryBarrier:
1517 case glslang::EOpMemoryBarrierAtomicCounter:
1518 case glslang::EOpMemoryBarrierBuffer:
1519 case glslang::EOpMemoryBarrierImage:
1520 case glslang::EOpMemoryBarrierShared:
1521 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001522 case glslang::EOpAllMemoryBarrierWithGroupSync:
1523 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1524 case glslang::EOpWorkgroupMemoryBarrier:
1525 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001526 noReturnValue = true;
1527 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1528 break;
1529
John Kessenich426394d2015-07-23 10:22:48 -06001530 case glslang::EOpAtomicAdd:
1531 case glslang::EOpAtomicMin:
1532 case glslang::EOpAtomicMax:
1533 case glslang::EOpAtomicAnd:
1534 case glslang::EOpAtomicOr:
1535 case glslang::EOpAtomicXor:
1536 case glslang::EOpAtomicExchange:
1537 case glslang::EOpAtomicCompSwap:
1538 atomic = true;
1539 break;
1540
John Kessenich140f3df2015-06-26 16:58:36 -06001541 default:
1542 break;
1543 }
1544
1545 //
1546 // See if it maps to a regular operation.
1547 //
John Kessenich140f3df2015-06-26 16:58:36 -06001548 if (binOp != glslang::EOpNull) {
1549 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1550 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1551 assert(left && right);
1552
1553 builder.clearAccessChain();
1554 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001555 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001556
1557 builder.clearAccessChain();
1558 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001559 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001560
qining25262b32016-05-06 17:25:16 -04001561 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001562 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001563 left->getType().getBasicType(), reduceComparison);
1564
1565 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001566 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001567 builder.clearAccessChain();
1568 builder.setAccessChainRValue(result);
1569
1570 return false;
1571 }
1572
John Kessenich426394d2015-07-23 10:22:48 -06001573 //
1574 // Create the list of operands.
1575 //
John Kessenich140f3df2015-06-26 16:58:36 -06001576 glslang::TIntermSequence& glslangOperands = node->getSequence();
1577 std::vector<spv::Id> operands;
1578 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001579 // special case l-value operands; there are just a few
1580 bool lvalue = false;
1581 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001582 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001583 case glslang::EOpModf:
1584 if (arg == 1)
1585 lvalue = true;
1586 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001587 case glslang::EOpInterpolateAtSample:
1588 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001589#ifdef AMD_EXTENSIONS
1590 case glslang::EOpInterpolateAtVertex:
1591#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001592 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001593 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001594
1595 // Does it need a swizzle inversion? If so, evaluation is inverted;
1596 // operate first on the swizzle base, then apply the swizzle.
1597 if (glslangOperands[0]->getAsOperator() &&
1598 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1599 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1600 }
Rex Xu7a26c172015-12-08 17:12:09 +08001601 break;
Rex Xud4782c12015-09-06 16:30:11 +08001602 case glslang::EOpAtomicAdd:
1603 case glslang::EOpAtomicMin:
1604 case glslang::EOpAtomicMax:
1605 case glslang::EOpAtomicAnd:
1606 case glslang::EOpAtomicOr:
1607 case glslang::EOpAtomicXor:
1608 case glslang::EOpAtomicExchange:
1609 case glslang::EOpAtomicCompSwap:
1610 if (arg == 0)
1611 lvalue = true;
1612 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001613 case glslang::EOpAddCarry:
1614 case glslang::EOpSubBorrow:
1615 if (arg == 2)
1616 lvalue = true;
1617 break;
1618 case glslang::EOpUMulExtended:
1619 case glslang::EOpIMulExtended:
1620 if (arg >= 2)
1621 lvalue = true;
1622 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001623 default:
1624 break;
1625 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001626 builder.clearAccessChain();
1627 if (invertedType != spv::NoType && arg == 0)
1628 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1629 else
1630 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001631 if (lvalue)
1632 operands.push_back(builder.accessChainGetLValue());
1633 else
John Kessenich32cfd492016-02-02 12:37:46 -07001634 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001635 }
John Kessenich426394d2015-07-23 10:22:48 -06001636
1637 if (atomic) {
1638 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001639 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001640 } else {
1641 // Pass through to generic operations.
1642 switch (glslangOperands.size()) {
1643 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001644 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001645 break;
1646 case 1:
qining25262b32016-05-06 17:25:16 -04001647 result = createUnaryOperation(
1648 node->getOp(), precision,
1649 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001650 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001651 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001652 break;
1653 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001654 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001655 break;
1656 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001657 if (invertedType)
1658 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001659 }
1660
1661 if (noReturnValue)
1662 return false;
1663
1664 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001665 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001666 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001667 } else {
1668 builder.clearAccessChain();
1669 builder.setAccessChainRValue(result);
1670 return false;
1671 }
1672}
1673
1674bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1675{
1676 // This path handles both if-then-else and ?:
1677 // The if-then-else has a node type of void, while
1678 // ?: has a non-void node type
1679 spv::Id result = 0;
1680 if (node->getBasicType() != glslang::EbtVoid) {
1681 // don't handle this as just on-the-fly temporaries, because there will be two names
1682 // and better to leave SSA to later passes
1683 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1684 }
1685
1686 // emit the condition before doing anything with selection
1687 node->getCondition()->traverse(this);
1688
1689 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001690 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001691
1692 if (node->getTrueBlock()) {
1693 // emit the "then" statement
1694 node->getTrueBlock()->traverse(this);
1695 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001696 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001697 }
1698
1699 if (node->getFalseBlock()) {
1700 ifBuilder.makeBeginElse();
1701 // emit the "else" statement
1702 node->getFalseBlock()->traverse(this);
1703 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001704 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001705 }
1706
1707 ifBuilder.makeEndIf();
1708
1709 if (result) {
1710 // GLSL only has r-values as the result of a :?, but
1711 // if we have an l-value, that can be more efficient if it will
1712 // become the base of a complex r-value expression, because the
1713 // next layer copies r-values into memory to use the access-chain mechanism
1714 builder.clearAccessChain();
1715 builder.setAccessChainLValue(result);
1716 }
1717
1718 return false;
1719}
1720
1721bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1722{
1723 // emit and get the condition before doing anything with switch
1724 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001725 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001726
1727 // browse the children to sort out code segments
1728 int defaultSegment = -1;
1729 std::vector<TIntermNode*> codeSegments;
1730 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1731 std::vector<int> caseValues;
1732 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1733 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1734 TIntermNode* child = *c;
1735 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001736 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001737 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001738 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001739 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1740 } else
1741 codeSegments.push_back(child);
1742 }
1743
qining25262b32016-05-06 17:25:16 -04001744 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001745 // statements between the last case and the end of the switch statement
1746 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1747 (int)codeSegments.size() == defaultSegment)
1748 codeSegments.push_back(nullptr);
1749
1750 // make the switch statement
1751 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001752 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001753
1754 // emit all the code in the segments
1755 breakForLoop.push(false);
1756 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1757 builder.nextSwitchSegment(segmentBlocks, s);
1758 if (codeSegments[s])
1759 codeSegments[s]->traverse(this);
1760 else
1761 builder.addSwitchBreak();
1762 }
1763 breakForLoop.pop();
1764
1765 builder.endSwitch(segmentBlocks);
1766
1767 return false;
1768}
1769
1770void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1771{
1772 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001773 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001774
1775 builder.clearAccessChain();
1776 builder.setAccessChainRValue(constant);
1777}
1778
1779bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1780{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001781 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001782 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001783 // Spec requires back edges to target header blocks, and every header block
1784 // must dominate its merge block. Make a header block first to ensure these
1785 // conditions are met. By definition, it will contain OpLoopMerge, followed
1786 // by a block-ending branch. But we don't want to put any other body/test
1787 // instructions in it, since the body/test may have arbitrary instructions,
1788 // including merges of its own.
1789 builder.setBuildPoint(&blocks.head);
1790 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001791 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001792 spv::Block& test = builder.makeNewBlock();
1793 builder.createBranch(&test);
1794
1795 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001796 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001797 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001798 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001799 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1800
1801 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001802 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001803 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001804 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001805 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001806 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001807
1808 builder.setBuildPoint(&blocks.continue_target);
1809 if (node->getTerminal())
1810 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001811 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001812 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001813 builder.createBranch(&blocks.body);
1814
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001815 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001816 builder.setBuildPoint(&blocks.body);
1817 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001818 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001819 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001820 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001821
1822 builder.setBuildPoint(&blocks.continue_target);
1823 if (node->getTerminal())
1824 node->getTerminal()->traverse(this);
1825 if (node->getTest()) {
1826 node->getTest()->traverse(this);
1827 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001828 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001829 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001830 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001831 // TODO: unless there was a break/return/discard instruction
1832 // somewhere in the body, this is an infinite loop, so we should
1833 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001834 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001835 }
John Kessenich140f3df2015-06-26 16:58:36 -06001836 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001837 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001838 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001839 return false;
1840}
1841
1842bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1843{
1844 if (node->getExpression())
1845 node->getExpression()->traverse(this);
1846
1847 switch (node->getFlowOp()) {
1848 case glslang::EOpKill:
1849 builder.makeDiscard();
1850 break;
1851 case glslang::EOpBreak:
1852 if (breakForLoop.top())
1853 builder.createLoopExit();
1854 else
1855 builder.addSwitchBreak();
1856 break;
1857 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001858 builder.createLoopContinue();
1859 break;
1860 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001861 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001862 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001863 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001864 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001865
1866 builder.clearAccessChain();
1867 break;
1868
1869 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001870 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001871 break;
1872 }
1873
1874 return false;
1875}
1876
1877spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1878{
qining25262b32016-05-06 17:25:16 -04001879 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001880 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001881 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001882 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001883 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001884 }
1885
1886 // Now, handle actual variables
1887 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1888 spv::Id spvType = convertGlslangToSpvType(node->getType());
1889
1890 const char* name = node->getName().c_str();
1891 if (glslang::IsAnonymous(name))
1892 name = "";
1893
1894 return builder.createVariable(storageClass, spvType, name);
1895}
1896
1897// Return type Id of the sampled type.
1898spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1899{
1900 switch (sampler.type) {
1901 case glslang::EbtFloat: return builder.makeFloatType(32);
1902 case glslang::EbtInt: return builder.makeIntType(32);
1903 case glslang::EbtUint: return builder.makeUintType(32);
1904 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001905 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001906 return builder.makeFloatType(32);
1907 }
1908}
1909
John Kessenich8c8505c2016-07-26 12:50:38 -06001910// If node is a swizzle operation, return the type that should be used if
1911// the swizzle base is first consumed by another operation, before the swizzle
1912// is applied.
1913spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1914{
1915 if (node.getAsOperator() &&
1916 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1917 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1918 else
1919 return spv::NoType;
1920}
1921
1922// When inverting a swizzle with a parent op, this function
1923// will apply the swizzle operation to a completed parent operation.
1924spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1925{
1926 std::vector<unsigned> swizzle;
1927 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1928 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1929}
1930
John Kessenich8c8505c2016-07-26 12:50:38 -06001931// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1932void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1933{
1934 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1935 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1936 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1937}
1938
John Kessenich3ac051e2015-12-20 11:29:16 -07001939// Convert from a glslang type to an SPV type, by calling into a
1940// recursive version of this function. This establishes the inherited
1941// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001942spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1943{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001944 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001945}
1946
1947// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001948// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001949// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001950spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001951{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001952 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001953
1954 switch (type.getBasicType()) {
1955 case glslang::EbtVoid:
1956 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001957 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001958 break;
1959 case glslang::EbtFloat:
1960 spvType = builder.makeFloatType(32);
1961 break;
1962 case glslang::EbtDouble:
1963 spvType = builder.makeFloatType(64);
1964 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001965#ifdef AMD_EXTENSIONS
1966 case glslang::EbtFloat16:
1967 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
1968 builder.addCapability(spv::CapabilityFloat16);
1969 spvType = builder.makeFloatType(16);
1970 break;
1971#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001972 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001973 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1974 // a 32-bit int where non-0 means true.
1975 if (explicitLayout != glslang::ElpNone)
1976 spvType = builder.makeUintType(32);
1977 else
1978 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001979 break;
1980 case glslang::EbtInt:
1981 spvType = builder.makeIntType(32);
1982 break;
1983 case glslang::EbtUint:
1984 spvType = builder.makeUintType(32);
1985 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001986 case glslang::EbtInt64:
1987 builder.addCapability(spv::CapabilityInt64);
1988 spvType = builder.makeIntType(64);
1989 break;
1990 case glslang::EbtUint64:
1991 builder.addCapability(spv::CapabilityInt64);
1992 spvType = builder.makeUintType(64);
1993 break;
John Kessenich426394d2015-07-23 10:22:48 -06001994 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06001995 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06001996 spvType = builder.makeUintType(32);
1997 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001998 case glslang::EbtSampler:
1999 {
2000 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002001 if (sampler.sampler) {
2002 // pure sampler
2003 spvType = builder.makeSamplerType();
2004 } else {
2005 // an image is present, make its type
2006 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2007 sampler.image ? 2 : 1, TranslateImageFormat(type));
2008 if (sampler.combined) {
2009 // already has both image and sampler, make the combined type
2010 spvType = builder.makeSampledImageType(spvType);
2011 }
John Kessenich55e7d112015-11-15 21:33:39 -07002012 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002013 }
John Kessenich140f3df2015-06-26 16:58:36 -06002014 break;
2015 case glslang::EbtStruct:
2016 case glslang::EbtBlock:
2017 {
2018 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002019 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002020
2021 // Try to share structs for different layouts, but not yet for other
2022 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002023 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002024 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002025 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002026 break;
2027
2028 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002029 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002030 memberRemapper[glslangMembers].resize(glslangMembers->size());
2031 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002032 }
2033 break;
2034 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002035 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002036 break;
2037 }
2038
2039 if (type.isMatrix())
2040 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2041 else {
2042 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2043 if (type.getVectorSize() > 1)
2044 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2045 }
2046
2047 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002048 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2049
John Kessenichc9a80832015-09-12 12:17:44 -06002050 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002051 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002052 // We need to decorate array strides for types needing explicit layout, except blocks.
2053 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002054 // Use a dummy glslang type for querying internal strides of
2055 // arrays of arrays, but using just a one-dimensional array.
2056 glslang::TType simpleArrayType(type, 0); // deference type of the array
2057 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2058 simpleArrayType.getArraySizes().dereference();
2059
2060 // Will compute the higher-order strides here, rather than making a whole
2061 // pile of types and doing repetitive recursion on their contents.
2062 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2063 }
John Kessenichf8842e52016-01-04 19:22:56 -07002064
2065 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002066 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002067 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002068 if (stride > 0)
2069 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002070 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002071 }
2072 } else {
2073 // single-dimensional array, and don't yet have stride
2074
John Kessenichf8842e52016-01-04 19:22:56 -07002075 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002076 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2077 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002078 }
John Kessenich31ed4832015-09-09 17:51:38 -06002079
John Kessenichc9a80832015-09-12 12:17:44 -06002080 // Do the outer dimension, which might not be known for a runtime-sized array
2081 if (type.isRuntimeSizedArray()) {
2082 spvType = builder.makeRuntimeArray(spvType);
2083 } else {
2084 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002085 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002086 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002087 if (stride > 0)
2088 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002089 }
2090
2091 return spvType;
2092}
2093
John Kessenich6090df02016-06-30 21:18:02 -06002094
2095// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2096// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2097// Mutually recursive with convertGlslangToSpvType().
2098spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2099 const glslang::TTypeList* glslangMembers,
2100 glslang::TLayoutPacking explicitLayout,
2101 const glslang::TQualifier& qualifier)
2102{
2103 // Create a vector of struct types for SPIR-V to consume
2104 std::vector<spv::Id> spvMembers;
2105 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2106 int locationOffset = 0; // for use across struct members, when they are called recursively
2107 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2108 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2109 if (glslangMember.hiddenMember()) {
2110 ++memberDelta;
2111 if (type.getBasicType() == glslang::EbtBlock)
2112 memberRemapper[glslangMembers][i] = -1;
2113 } else {
2114 if (type.getBasicType() == glslang::EbtBlock)
2115 memberRemapper[glslangMembers][i] = i - memberDelta;
2116 // modify just this child's view of the qualifier
2117 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2118 InheritQualifiers(memberQualifier, qualifier);
2119
2120 // manually inherit location; it's more complex
2121 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2122 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2123 if (qualifier.hasLocation())
2124 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2125
2126 // recurse
2127 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2128 }
2129 }
2130
2131 // Make the SPIR-V type
2132 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002133 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002134 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2135
2136 // Decorate it
2137 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2138
2139 return spvType;
2140}
2141
2142void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2143 const glslang::TTypeList* glslangMembers,
2144 glslang::TLayoutPacking explicitLayout,
2145 const glslang::TQualifier& qualifier,
2146 spv::Id spvType)
2147{
2148 // Name and decorate the non-hidden members
2149 int offset = -1;
2150 int locationOffset = 0; // for use within the members of this struct
2151 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2152 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2153 int member = i;
2154 if (type.getBasicType() == glslang::EbtBlock)
2155 member = memberRemapper[glslangMembers][i];
2156
2157 // modify just this child's view of the qualifier
2158 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2159 InheritQualifiers(memberQualifier, qualifier);
2160
2161 // using -1 above to indicate a hidden member
2162 if (member >= 0) {
2163 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2164 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2165 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2166 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2167 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2168 if (type.getBasicType() == glslang::EbtBlock) {
2169 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2170 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2171 }
2172 }
2173 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2174
2175 if (qualifier.storage == glslang::EvqBuffer) {
2176 std::vector<spv::Decoration> memory;
2177 TranslateMemoryDecoration(memberQualifier, memory);
2178 for (unsigned int i = 0; i < memory.size(); ++i)
2179 addMemberDecoration(spvType, member, memory[i]);
2180 }
2181
John Kessenich2f47bc92016-06-30 21:47:35 -06002182 // Compute location decoration; tricky based on whether inheritance is at play and
2183 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002184 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2185 // probably move to the linker stage of the front end proper, and just have the
2186 // answer sitting already distributed throughout the individual member locations.
2187 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002188 // Ignore member locations if the container is an array, as that's
2189 // ill-specified and decisions have been made to not allow this anyway.
2190 // The object itself must have a location, and that comes out from decorating the object,
2191 // not the type (this code decorates types).
2192 if (! type.isArray()) {
2193 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2194 // struct members should not have explicit locations
2195 assert(type.getBasicType() != glslang::EbtStruct);
2196 location = memberQualifier.layoutLocation;
2197 } else if (type.getBasicType() != glslang::EbtBlock) {
2198 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2199 // The members, and their nested types, must not themselves have Location decorations.
2200 } else if (qualifier.hasLocation()) // inheritance
2201 location = qualifier.layoutLocation + locationOffset;
2202 }
John Kessenich6090df02016-06-30 21:18:02 -06002203 if (location >= 0)
2204 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2205
John Kessenich2f47bc92016-06-30 21:47:35 -06002206 if (qualifier.hasLocation()) // track for upcoming inheritance
2207 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2208
John Kessenich6090df02016-06-30 21:18:02 -06002209 // component, XFB, others
2210 if (glslangMember.getQualifier().hasComponent())
2211 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2212 if (glslangMember.getQualifier().hasXfbOffset())
2213 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2214 else if (explicitLayout != glslang::ElpNone) {
2215 // figure out what to do with offset, which is accumulating
2216 int nextOffset;
2217 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2218 if (offset >= 0)
2219 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2220 offset = nextOffset;
2221 }
2222
2223 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2224 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2225
2226 // built-in variable decorations
2227 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002228 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002229 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2230 }
2231 }
2232
2233 // Decorate the structure
2234 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2235 addDecoration(spvType, TranslateBlockDecoration(type));
2236 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2237 builder.addCapability(spv::CapabilityGeometryStreams);
2238 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2239 }
2240 if (glslangIntermediate->getXfbMode()) {
2241 builder.addCapability(spv::CapabilityTransformFeedback);
2242 if (type.getQualifier().hasXfbStride())
2243 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2244 if (type.getQualifier().hasXfbBuffer())
2245 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2246 }
2247}
2248
John Kessenich6c292d32016-02-15 20:58:50 -07002249// Turn the expression forming the array size into an id.
2250// This is not quite trivial, because of specialization constants.
2251// Sometimes, a raw constant is turned into an Id, and sometimes
2252// a specialization constant expression is.
2253spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2254{
2255 // First, see if this is sized with a node, meaning a specialization constant:
2256 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2257 if (specNode != nullptr) {
2258 builder.clearAccessChain();
2259 specNode->traverse(this);
2260 return accessChainLoad(specNode->getAsTyped()->getType());
2261 }
qining25262b32016-05-06 17:25:16 -04002262
John Kessenich6c292d32016-02-15 20:58:50 -07002263 // Otherwise, need a compile-time (front end) size, get it:
2264 int size = arraySizes.getDimSize(dim);
2265 assert(size > 0);
2266 return builder.makeUintConstant(size);
2267}
2268
John Kessenich103bef92016-02-08 21:38:15 -07002269// Wrap the builder's accessChainLoad to:
2270// - localize handling of RelaxedPrecision
2271// - use the SPIR-V inferred type instead of another conversion of the glslang type
2272// (avoids unnecessary work and possible type punning for structures)
2273// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002274spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2275{
John Kessenich103bef92016-02-08 21:38:15 -07002276 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2277 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2278
2279 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002280 if (type.getBasicType() == glslang::EbtBool) {
2281 if (builder.isScalarType(nominalTypeId)) {
2282 // Conversion for bool
2283 spv::Id boolType = builder.makeBoolType();
2284 if (nominalTypeId != boolType)
2285 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2286 } else if (builder.isVectorType(nominalTypeId)) {
2287 // Conversion for bvec
2288 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2289 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2290 if (nominalTypeId != bvecType)
2291 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2292 }
2293 }
John Kessenich103bef92016-02-08 21:38:15 -07002294
2295 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002296}
2297
Rex Xu27253232016-02-23 17:51:09 +08002298// Wrap the builder's accessChainStore to:
2299// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002300//
2301// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002302void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2303{
2304 // Need to convert to abstract types when necessary
2305 if (type.getBasicType() == glslang::EbtBool) {
2306 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2307
2308 if (builder.isScalarType(nominalTypeId)) {
2309 // Conversion for bool
2310 spv::Id boolType = builder.makeBoolType();
2311 if (nominalTypeId != boolType) {
2312 spv::Id zero = builder.makeUintConstant(0);
2313 spv::Id one = builder.makeUintConstant(1);
2314 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2315 }
2316 } else if (builder.isVectorType(nominalTypeId)) {
2317 // Conversion for bvec
2318 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2319 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2320 if (nominalTypeId != bvecType) {
2321 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2322 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2323 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2324 }
2325 }
2326 }
2327
2328 builder.accessChainStore(rvalue);
2329}
2330
John Kessenich4bf71552016-09-02 11:20:21 -06002331// For storing when types match at the glslang level, but not might match at the
2332// SPIR-V level.
2333//
2334// This especially happens when a single glslang type expands to multiple
2335// SPIR-V types, like a struct that is used in an member-undecorated way as well
2336// as in a member-decorated way.
2337//
2338// NOTE: This function can handle any store request; if it's not special it
2339// simplifies to a simple OpStore.
2340//
2341// Implicitly uses the existing builder.accessChain as the storage target.
2342void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2343{
John Kessenichb3e24e42016-09-11 12:33:43 -06002344 // we only do the complex path here if it's an aggregate
2345 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002346 accessChainStore(type, rValue);
2347 return;
2348 }
2349
John Kessenichb3e24e42016-09-11 12:33:43 -06002350 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002351 spv::Id rType = builder.getTypeId(rValue);
2352 spv::Id lValue = builder.accessChainGetLValue();
2353 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2354 if (lType == rType) {
2355 accessChainStore(type, rValue);
2356 return;
2357 }
2358
John Kessenichb3e24e42016-09-11 12:33:43 -06002359 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002360 // where the two types were the same type in GLSL. This requires member
2361 // by member copy, recursively.
2362
John Kessenichb3e24e42016-09-11 12:33:43 -06002363 // If an array, copy element by element.
2364 if (type.isArray()) {
2365 glslang::TType glslangElementType(type, 0);
2366 spv::Id elementRType = builder.getContainedTypeId(rType);
2367 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2368 // get the source member
2369 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002370
John Kessenichb3e24e42016-09-11 12:33:43 -06002371 // set up the target storage
2372 builder.clearAccessChain();
2373 builder.setAccessChainLValue(lValue);
2374 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002375
John Kessenichb3e24e42016-09-11 12:33:43 -06002376 // store the member
2377 multiTypeStore(glslangElementType, elementRValue);
2378 }
2379 } else {
2380 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002381
John Kessenichb3e24e42016-09-11 12:33:43 -06002382 // loop over structure members
2383 const glslang::TTypeList& members = *type.getStruct();
2384 for (int m = 0; m < (int)members.size(); ++m) {
2385 const glslang::TType& glslangMemberType = *members[m].type;
2386
2387 // get the source member
2388 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2389 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2390
2391 // set up the target storage
2392 builder.clearAccessChain();
2393 builder.setAccessChainLValue(lValue);
2394 builder.accessChainPush(builder.makeIntConstant(m));
2395
2396 // store the member
2397 multiTypeStore(glslangMemberType, memberRValue);
2398 }
John Kessenich4bf71552016-09-02 11:20:21 -06002399 }
2400}
2401
John Kessenichf85e8062015-12-19 13:57:10 -07002402// Decide whether or not this type should be
2403// decorated with offsets and strides, and if so
2404// whether std140 or std430 rules should be applied.
2405glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002406{
John Kessenichf85e8062015-12-19 13:57:10 -07002407 // has to be a block
2408 if (type.getBasicType() != glslang::EbtBlock)
2409 return glslang::ElpNone;
2410
2411 // has to be a uniform or buffer block
2412 if (type.getQualifier().storage != glslang::EvqUniform &&
2413 type.getQualifier().storage != glslang::EvqBuffer)
2414 return glslang::ElpNone;
2415
2416 // return the layout to use
2417 switch (type.getQualifier().layoutPacking) {
2418 case glslang::ElpStd140:
2419 case glslang::ElpStd430:
2420 return type.getQualifier().layoutPacking;
2421 default:
2422 return glslang::ElpNone;
2423 }
John Kessenich31ed4832015-09-09 17:51:38 -06002424}
2425
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002426// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002427int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002428{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002429 int size;
John Kessenich49987892015-12-29 17:11:44 -07002430 int stride;
2431 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002432
2433 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002434}
2435
John Kessenich49987892015-12-29 17:11:44 -07002436// 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 -07002437// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002438int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002439{
John Kessenich49987892015-12-29 17:11:44 -07002440 glslang::TType elementType;
2441 elementType.shallowCopy(matrixType);
2442 elementType.clearArraySizes();
2443
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002444 int size;
John Kessenich49987892015-12-29 17:11:44 -07002445 int stride;
2446 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2447
2448 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002449}
2450
John Kessenich5e4b1242015-08-06 22:53:06 -06002451// Given a member type of a struct, realign the current offset for it, and compute
2452// the next (not yet aligned) offset for the next member, which will get aligned
2453// on the next call.
2454// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2455// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2456// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002457void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002458 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002459{
2460 // this will get a positive value when deemed necessary
2461 nextOffset = -1;
2462
John Kessenich5e4b1242015-08-06 22:53:06 -06002463 // override anything in currentOffset with user-set offset
2464 if (memberType.getQualifier().hasOffset())
2465 currentOffset = memberType.getQualifier().layoutOffset;
2466
2467 // It could be that current linker usage in glslang updated all the layoutOffset,
2468 // in which case the following code does not matter. But, that's not quite right
2469 // once cross-compilation unit GLSL validation is done, as the original user
2470 // settings are needed in layoutOffset, and then the following will come into play.
2471
John Kessenichf85e8062015-12-19 13:57:10 -07002472 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002473 if (! memberType.getQualifier().hasOffset())
2474 currentOffset = -1;
2475
2476 return;
2477 }
2478
John Kessenichf85e8062015-12-19 13:57:10 -07002479 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002480 if (currentOffset < 0)
2481 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002482
John Kessenich5e4b1242015-08-06 22:53:06 -06002483 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2484 // but possibly not yet correctly aligned.
2485
2486 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002487 int dummyStride;
2488 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002489 glslang::RoundToPow2(currentOffset, memberAlignment);
2490 nextOffset = currentOffset + memberSize;
2491}
2492
David Netoa901ffe2016-06-08 14:11:40 +01002493void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002494{
David Netoa901ffe2016-06-08 14:11:40 +01002495 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2496 switch (glslangBuiltIn)
2497 {
2498 case glslang::EbvClipDistance:
2499 case glslang::EbvCullDistance:
2500 case glslang::EbvPointSize:
2501 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2502 // Alternately, we could just call this for any glslang built-in, since the
2503 // capability already guards against duplicates.
2504 TranslateBuiltInDecoration(glslangBuiltIn, false);
2505 break;
2506 default:
2507 // Capabilities were already generated when the struct was declared.
2508 break;
2509 }
John Kessenichebb50532016-05-16 19:22:05 -06002510}
2511
John Kessenich6fccb3c2016-09-19 16:01:41 -06002512bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002513{
John Kessenicheee9d532016-09-19 18:09:30 -06002514 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002515}
2516
2517// Make all the functions, skeletally, without actually visiting their bodies.
2518void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2519{
2520 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2521 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002522 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002523 continue;
2524
2525 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002526 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002527 //
qining25262b32016-05-06 17:25:16 -04002528 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002529 // function. What it is an address of varies:
2530 //
John Kessenich4bf71552016-09-02 11:20:21 -06002531 // - "in" parameters not marked as "const" can be written to without modifying the calling
2532 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002533 //
2534 // - "const in" parameters can just be the r-value, as no writes need occur.
2535 //
John Kessenich4bf71552016-09-02 11:20:21 -06002536 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2537 // 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 -06002538
2539 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002540 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002541 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2542
2543 for (int p = 0; p < (int)parameters.size(); ++p) {
2544 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2545 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002546 if (paramType.isOpaque())
2547 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2548 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002549 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2550 else
John Kessenich4bf71552016-09-02 11:20:21 -06002551 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002552 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002553 paramTypes.push_back(typeId);
2554 }
2555
2556 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002557 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2558 convertGlslangToSpvType(glslFunction->getType()),
2559 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002560
2561 // Track function to emit/call later
2562 functionMap[glslFunction->getName().c_str()] = function;
2563
2564 // Set the parameter id's
2565 for (int p = 0; p < (int)parameters.size(); ++p) {
2566 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2567 // give a name too
2568 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2569 }
2570 }
2571}
2572
2573// Process all the initializers, while skipping the functions and link objects
2574void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2575{
2576 builder.setBuildPoint(shaderEntry->getLastBlock());
2577 for (int i = 0; i < (int)initializers.size(); ++i) {
2578 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2579 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2580
2581 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002582 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002583 initializer->traverse(this);
2584 }
2585 }
2586}
2587
2588// Process all the functions, while skipping initializers.
2589void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2590{
2591 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2592 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2593 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2594 node->traverse(this);
2595 }
2596}
2597
2598void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2599{
qining25262b32016-05-06 17:25:16 -04002600 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002601 // that called makeFunctions().
2602 spv::Function* function = functionMap[node->getName().c_str()];
2603 spv::Block* functionBlock = function->getEntryBlock();
2604 builder.setBuildPoint(functionBlock);
2605}
2606
Rex Xu04db3f52015-09-16 11:44:02 +08002607void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002608{
Rex Xufc618912015-09-09 16:42:49 +08002609 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002610
2611 glslang::TSampler sampler = {};
2612 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002613 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002614 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2615 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2616 }
2617
John Kessenich140f3df2015-06-26 16:58:36 -06002618 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2619 builder.clearAccessChain();
2620 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002621
2622 // Special case l-value operands
2623 bool lvalue = false;
2624 switch (node.getOp()) {
2625 case glslang::EOpImageAtomicAdd:
2626 case glslang::EOpImageAtomicMin:
2627 case glslang::EOpImageAtomicMax:
2628 case glslang::EOpImageAtomicAnd:
2629 case glslang::EOpImageAtomicOr:
2630 case glslang::EOpImageAtomicXor:
2631 case glslang::EOpImageAtomicExchange:
2632 case glslang::EOpImageAtomicCompSwap:
2633 if (i == 0)
2634 lvalue = true;
2635 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002636 case glslang::EOpSparseImageLoad:
2637 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2638 lvalue = true;
2639 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002640 case glslang::EOpSparseTexture:
2641 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2642 lvalue = true;
2643 break;
2644 case glslang::EOpSparseTextureClamp:
2645 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2646 lvalue = true;
2647 break;
2648 case glslang::EOpSparseTextureLod:
2649 case glslang::EOpSparseTextureOffset:
2650 if (i == 3)
2651 lvalue = true;
2652 break;
2653 case glslang::EOpSparseTextureFetch:
2654 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2655 lvalue = true;
2656 break;
2657 case glslang::EOpSparseTextureFetchOffset:
2658 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2659 lvalue = true;
2660 break;
2661 case glslang::EOpSparseTextureLodOffset:
2662 case glslang::EOpSparseTextureGrad:
2663 case glslang::EOpSparseTextureOffsetClamp:
2664 if (i == 4)
2665 lvalue = true;
2666 break;
2667 case glslang::EOpSparseTextureGradOffset:
2668 case glslang::EOpSparseTextureGradClamp:
2669 if (i == 5)
2670 lvalue = true;
2671 break;
2672 case glslang::EOpSparseTextureGradOffsetClamp:
2673 if (i == 6)
2674 lvalue = true;
2675 break;
2676 case glslang::EOpSparseTextureGather:
2677 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2678 lvalue = true;
2679 break;
2680 case glslang::EOpSparseTextureGatherOffset:
2681 case glslang::EOpSparseTextureGatherOffsets:
2682 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2683 lvalue = true;
2684 break;
Rex Xufc618912015-09-09 16:42:49 +08002685 default:
2686 break;
2687 }
2688
Rex Xu6b86d492015-09-16 17:48:22 +08002689 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002690 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002691 else
John Kessenich32cfd492016-02-02 12:37:46 -07002692 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002693 }
2694}
2695
John Kessenichfc51d282015-08-19 13:34:18 -06002696void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002697{
John Kessenichfc51d282015-08-19 13:34:18 -06002698 builder.clearAccessChain();
2699 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002700 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002701}
John Kessenich140f3df2015-06-26 16:58:36 -06002702
John Kessenichfc51d282015-08-19 13:34:18 -06002703spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2704{
Rex Xufc618912015-09-09 16:42:49 +08002705 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002706 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002707 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002708 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002709
John Kessenichfc51d282015-08-19 13:34:18 -06002710 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002711 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2712 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2713 std::vector<spv::Id> arguments;
2714 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002715 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002716 else
2717 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002718 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002719
2720 spv::Builder::TextureParameters params = { };
2721 params.sampler = arguments[0];
2722
Rex Xu04db3f52015-09-16 11:44:02 +08002723 glslang::TCrackedTextureOp cracked;
2724 node->crackTexture(sampler, cracked);
2725
John Kessenichfc51d282015-08-19 13:34:18 -06002726 // Check for queries
2727 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002728 // a sampled image needs to have the image extracted first
2729 if (builder.isSampledImage(params.sampler))
2730 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002731 switch (node->getOp()) {
2732 case glslang::EOpImageQuerySize:
2733 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002734 if (arguments.size() > 1) {
2735 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002736 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002737 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002738 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002739 case glslang::EOpImageQuerySamples:
2740 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002741 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002742 case glslang::EOpTextureQueryLod:
2743 params.coords = arguments[1];
2744 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2745 case glslang::EOpTextureQueryLevels:
2746 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002747 case glslang::EOpSparseTexelsResident:
2748 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002749 default:
2750 assert(0);
2751 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002752 }
John Kessenich140f3df2015-06-26 16:58:36 -06002753 }
2754
Rex Xufc618912015-09-09 16:42:49 +08002755 // Check for image functions other than queries
2756 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002757 std::vector<spv::Id> operands;
2758 auto opIt = arguments.begin();
2759 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002760
2761 // Handle subpass operations
2762 // TODO: GLSL should change to have the "MS" only on the type rather than the
2763 // built-in function.
2764 if (cracked.subpass) {
2765 // add on the (0,0) coordinate
2766 spv::Id zero = builder.makeIntConstant(0);
2767 std::vector<spv::Id> comps;
2768 comps.push_back(zero);
2769 comps.push_back(zero);
2770 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2771 if (sampler.ms) {
2772 operands.push_back(spv::ImageOperandsSampleMask);
2773 operands.push_back(*(opIt++));
2774 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002775 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002776 }
2777
John Kessenich56bab042015-09-16 10:54:31 -06002778 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002779 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002780 if (sampler.ms) {
2781 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002782 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002783 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002784 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2785 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002786 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002787 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002788 if (sampler.ms) {
2789 operands.push_back(*(opIt + 1));
2790 operands.push_back(spv::ImageOperandsSampleMask);
2791 operands.push_back(*opIt);
2792 } else
2793 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002794 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002795 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2796 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002797 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002798 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2799 builder.addCapability(spv::CapabilitySparseResidency);
2800 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2801 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2802
2803 if (sampler.ms) {
2804 operands.push_back(spv::ImageOperandsSampleMask);
2805 operands.push_back(*opIt++);
2806 }
2807
2808 // Create the return type that was a special structure
2809 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002810 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002811 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2812 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2813
2814 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2815
2816 // Decode the return type
2817 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2818 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002819 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002820 // Process image atomic operations
2821
2822 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2823 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002824 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002825
John Kessenich8c8505c2016-07-26 12:50:38 -06002826 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002827 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002828
2829 std::vector<spv::Id> operands;
2830 operands.push_back(pointer);
2831 for (; opIt != arguments.end(); ++opIt)
2832 operands.push_back(*opIt);
2833
John Kessenich8c8505c2016-07-26 12:50:38 -06002834 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002835 }
2836 }
2837
2838 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002839 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002840 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2841
John Kessenichfc51d282015-08-19 13:34:18 -06002842 // check for bias argument
2843 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002844 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002845 int nonBiasArgCount = 2;
2846 if (cracked.offset)
2847 ++nonBiasArgCount;
2848 if (cracked.grad)
2849 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002850 if (cracked.lodClamp)
2851 ++nonBiasArgCount;
2852 if (sparse)
2853 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002854
2855 if ((int)arguments.size() > nonBiasArgCount)
2856 bias = true;
2857 }
2858
John Kessenicha5c33d62016-06-02 23:45:21 -06002859 // See if the sampler param should really be just the SPV image part
2860 if (cracked.fetch) {
2861 // a fetch needs to have the image extracted first
2862 if (builder.isSampledImage(params.sampler))
2863 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2864 }
2865
John Kessenichfc51d282015-08-19 13:34:18 -06002866 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002867
John Kessenichfc51d282015-08-19 13:34:18 -06002868 params.coords = arguments[1];
2869 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002870 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002871
2872 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002873 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002874 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002875 ++extraArgs;
2876 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002877 params.Dref = arguments[2];
2878 ++extraArgs;
2879 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002880 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002881 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002882 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002883 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002884 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002885 dRefComp = builder.getNumComponents(params.coords) - 1;
2886 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002887 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2888 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002889
2890 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002891 if (cracked.lod) {
2892 params.lod = arguments[2];
2893 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002894 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2895 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2896 noImplicitLod = true;
2897 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002898
2899 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002900 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002901 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002902 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002903 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002904
2905 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002906 if (cracked.grad) {
2907 params.gradX = arguments[2 + extraArgs];
2908 params.gradY = arguments[3 + extraArgs];
2909 extraArgs += 2;
2910 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002911
2912 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002913 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002914 params.offset = arguments[2 + extraArgs];
2915 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002916 } else if (cracked.offsets) {
2917 params.offsets = arguments[2 + extraArgs];
2918 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002919 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002920
2921 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002922 if (cracked.lodClamp) {
2923 params.lodClamp = arguments[2 + extraArgs];
2924 ++extraArgs;
2925 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002926
2927 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002928 if (sparse) {
2929 params.texelOut = arguments[2 + extraArgs];
2930 ++extraArgs;
2931 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002932
2933 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002934 if (bias) {
2935 params.bias = arguments[2 + extraArgs];
2936 ++extraArgs;
2937 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002938
2939 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002940 if (cracked.gather && ! sampler.shadow) {
2941 // default component is 0, if missing, otherwise an argument
2942 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002943 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002944 ++extraArgs;
2945 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002946 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002947 }
2948 }
John Kessenichfc51d282015-08-19 13:34:18 -06002949
John Kessenich65336482016-06-16 14:06:26 -06002950 // projective component (might not to move)
2951 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2952 // are divided by the last component of P."
2953 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2954 // unused components will appear after all used components."
2955 if (cracked.proj) {
2956 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2957 int projTargetComp;
2958 switch (sampler.dim) {
2959 case glslang::Esd1D: projTargetComp = 1; break;
2960 case glslang::Esd2D: projTargetComp = 2; break;
2961 case glslang::EsdRect: projTargetComp = 2; break;
2962 default: projTargetComp = projSourceComp; break;
2963 }
2964 // copy the projective coordinate if we have to
2965 if (projTargetComp != projSourceComp) {
2966 spv::Id projComp = builder.createCompositeExtract(params.coords,
2967 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2968 projSourceComp);
2969 params.coords = builder.createCompositeInsert(projComp, params.coords,
2970 builder.getTypeId(params.coords), projTargetComp);
2971 }
2972 }
2973
John Kessenich8c8505c2016-07-26 12:50:38 -06002974 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002975}
2976
2977spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2978{
2979 // Grab the function's pointer from the previously created function
2980 spv::Function* function = functionMap[node->getName().c_str()];
2981 if (! function)
2982 return 0;
2983
2984 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2985 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2986
2987 // See comments in makeFunctions() for details about the semantics for parameter passing.
2988 //
2989 // These imply we need a four step process:
2990 // 1. Evaluate the arguments
2991 // 2. Allocate and make copies of in, out, and inout arguments
2992 // 3. Make the call
2993 // 4. Copy back the results
2994
2995 // 1. Evaluate the arguments
2996 std::vector<spv::Builder::AccessChain> lValues;
2997 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002998 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002999 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003000 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003001 // build l-value
3002 builder.clearAccessChain();
3003 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003004 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003005 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07003006 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003007 // save l-value
3008 lValues.push_back(builder.getAccessChain());
3009 } else {
3010 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003011 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003012 }
3013 }
3014
3015 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3016 // copy the original into that space.
3017 //
3018 // Also, build up the list of actual arguments to pass in for the call
3019 int lValueCount = 0;
3020 int rValueCount = 0;
3021 std::vector<spv::Id> spvArgs;
3022 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003023 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003024 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07003025 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003026 builder.setAccessChain(lValues[lValueCount]);
3027 arg = builder.accessChainGetLValue();
3028 ++lValueCount;
3029 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003030 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003031 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3032 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3033 // need to copy the input into output space
3034 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003035 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003036 builder.clearAccessChain();
3037 builder.setAccessChainLValue(arg);
3038 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003039 }
3040 ++lValueCount;
3041 } else {
3042 arg = rValues[rValueCount];
3043 ++rValueCount;
3044 }
3045 spvArgs.push_back(arg);
3046 }
3047
3048 // 3. Make the call.
3049 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003050 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003051
3052 // 4. Copy back out an "out" arguments.
3053 lValueCount = 0;
3054 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003055 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003056 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3057 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3058 spv::Id copy = builder.createLoad(spvArgs[a]);
3059 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003060 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003061 }
3062 ++lValueCount;
3063 }
3064 }
3065
3066 return result;
3067}
3068
3069// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003070spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3071 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003072 spv::Id typeId, spv::Id left, spv::Id right,
3073 glslang::TBasicType typeProxy, bool reduceComparison)
3074{
Rex Xu8ff43de2016-04-22 16:51:45 +08003075 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003076#ifdef AMD_EXTENSIONS
3077 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3078#else
John Kessenich140f3df2015-06-26 16:58:36 -06003079 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003080#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003081 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003082
3083 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003084 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003085 bool comparison = false;
3086
3087 switch (op) {
3088 case glslang::EOpAdd:
3089 case glslang::EOpAddAssign:
3090 if (isFloat)
3091 binOp = spv::OpFAdd;
3092 else
3093 binOp = spv::OpIAdd;
3094 break;
3095 case glslang::EOpSub:
3096 case glslang::EOpSubAssign:
3097 if (isFloat)
3098 binOp = spv::OpFSub;
3099 else
3100 binOp = spv::OpISub;
3101 break;
3102 case glslang::EOpMul:
3103 case glslang::EOpMulAssign:
3104 if (isFloat)
3105 binOp = spv::OpFMul;
3106 else
3107 binOp = spv::OpIMul;
3108 break;
3109 case glslang::EOpVectorTimesScalar:
3110 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003111 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003112 if (builder.isVector(right))
3113 std::swap(left, right);
3114 assert(builder.isScalar(right));
3115 needMatchingVectors = false;
3116 binOp = spv::OpVectorTimesScalar;
3117 } else
3118 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003119 break;
3120 case glslang::EOpVectorTimesMatrix:
3121 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003122 binOp = spv::OpVectorTimesMatrix;
3123 break;
3124 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003125 binOp = spv::OpMatrixTimesVector;
3126 break;
3127 case glslang::EOpMatrixTimesScalar:
3128 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003129 binOp = spv::OpMatrixTimesScalar;
3130 break;
3131 case glslang::EOpMatrixTimesMatrix:
3132 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003133 binOp = spv::OpMatrixTimesMatrix;
3134 break;
3135 case glslang::EOpOuterProduct:
3136 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003137 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003138 break;
3139
3140 case glslang::EOpDiv:
3141 case glslang::EOpDivAssign:
3142 if (isFloat)
3143 binOp = spv::OpFDiv;
3144 else if (isUnsigned)
3145 binOp = spv::OpUDiv;
3146 else
3147 binOp = spv::OpSDiv;
3148 break;
3149 case glslang::EOpMod:
3150 case glslang::EOpModAssign:
3151 if (isFloat)
3152 binOp = spv::OpFMod;
3153 else if (isUnsigned)
3154 binOp = spv::OpUMod;
3155 else
3156 binOp = spv::OpSMod;
3157 break;
3158 case glslang::EOpRightShift:
3159 case glslang::EOpRightShiftAssign:
3160 if (isUnsigned)
3161 binOp = spv::OpShiftRightLogical;
3162 else
3163 binOp = spv::OpShiftRightArithmetic;
3164 break;
3165 case glslang::EOpLeftShift:
3166 case glslang::EOpLeftShiftAssign:
3167 binOp = spv::OpShiftLeftLogical;
3168 break;
3169 case glslang::EOpAnd:
3170 case glslang::EOpAndAssign:
3171 binOp = spv::OpBitwiseAnd;
3172 break;
3173 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003174 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003175 binOp = spv::OpLogicalAnd;
3176 break;
3177 case glslang::EOpInclusiveOr:
3178 case glslang::EOpInclusiveOrAssign:
3179 binOp = spv::OpBitwiseOr;
3180 break;
3181 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003182 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003183 binOp = spv::OpLogicalOr;
3184 break;
3185 case glslang::EOpExclusiveOr:
3186 case glslang::EOpExclusiveOrAssign:
3187 binOp = spv::OpBitwiseXor;
3188 break;
3189 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003190 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003191 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003192 break;
3193
3194 case glslang::EOpLessThan:
3195 case glslang::EOpGreaterThan:
3196 case glslang::EOpLessThanEqual:
3197 case glslang::EOpGreaterThanEqual:
3198 case glslang::EOpEqual:
3199 case glslang::EOpNotEqual:
3200 case glslang::EOpVectorEqual:
3201 case glslang::EOpVectorNotEqual:
3202 comparison = true;
3203 break;
3204 default:
3205 break;
3206 }
3207
John Kessenich7c1aa102015-10-15 13:29:11 -06003208 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003209 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003210 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003211 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003212 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003213
3214 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003215 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003216 builder.promoteScalar(precision, left, right);
3217
qining25262b32016-05-06 17:25:16 -04003218 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3219 addDecoration(result, noContraction);
3220 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003221 }
3222
3223 if (! comparison)
3224 return 0;
3225
John Kessenich7c1aa102015-10-15 13:29:11 -06003226 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003227
John Kessenich4583b612016-08-07 19:14:22 -06003228 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3229 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003230 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003231
3232 switch (op) {
3233 case glslang::EOpLessThan:
3234 if (isFloat)
3235 binOp = spv::OpFOrdLessThan;
3236 else if (isUnsigned)
3237 binOp = spv::OpULessThan;
3238 else
3239 binOp = spv::OpSLessThan;
3240 break;
3241 case glslang::EOpGreaterThan:
3242 if (isFloat)
3243 binOp = spv::OpFOrdGreaterThan;
3244 else if (isUnsigned)
3245 binOp = spv::OpUGreaterThan;
3246 else
3247 binOp = spv::OpSGreaterThan;
3248 break;
3249 case glslang::EOpLessThanEqual:
3250 if (isFloat)
3251 binOp = spv::OpFOrdLessThanEqual;
3252 else if (isUnsigned)
3253 binOp = spv::OpULessThanEqual;
3254 else
3255 binOp = spv::OpSLessThanEqual;
3256 break;
3257 case glslang::EOpGreaterThanEqual:
3258 if (isFloat)
3259 binOp = spv::OpFOrdGreaterThanEqual;
3260 else if (isUnsigned)
3261 binOp = spv::OpUGreaterThanEqual;
3262 else
3263 binOp = spv::OpSGreaterThanEqual;
3264 break;
3265 case glslang::EOpEqual:
3266 case glslang::EOpVectorEqual:
3267 if (isFloat)
3268 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003269 else if (isBool)
3270 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003271 else
3272 binOp = spv::OpIEqual;
3273 break;
3274 case glslang::EOpNotEqual:
3275 case glslang::EOpVectorNotEqual:
3276 if (isFloat)
3277 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003278 else if (isBool)
3279 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003280 else
3281 binOp = spv::OpINotEqual;
3282 break;
3283 default:
3284 break;
3285 }
3286
qining25262b32016-05-06 17:25:16 -04003287 if (binOp != spv::OpNop) {
3288 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3289 addDecoration(result, noContraction);
3290 return builder.setPrecision(result, precision);
3291 }
John Kessenich140f3df2015-06-26 16:58:36 -06003292
3293 return 0;
3294}
3295
John Kessenich04bb8a02015-12-12 12:28:14 -07003296//
3297// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3298// These can be any of:
3299//
3300// matrix * scalar
3301// scalar * matrix
3302// matrix * matrix linear algebraic
3303// matrix * vector
3304// vector * matrix
3305// matrix * matrix componentwise
3306// matrix op matrix op in {+, -, /}
3307// matrix op scalar op in {+, -, /}
3308// scalar op matrix op in {+, -, /}
3309//
qining25262b32016-05-06 17:25:16 -04003310spv::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 -07003311{
3312 bool firstClass = true;
3313
3314 // First, handle first-class matrix operations (* and matrix/scalar)
3315 switch (op) {
3316 case spv::OpFDiv:
3317 if (builder.isMatrix(left) && builder.isScalar(right)) {
3318 // turn matrix / scalar into a multiply...
3319 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3320 op = spv::OpMatrixTimesScalar;
3321 } else
3322 firstClass = false;
3323 break;
3324 case spv::OpMatrixTimesScalar:
3325 if (builder.isMatrix(right))
3326 std::swap(left, right);
3327 assert(builder.isScalar(right));
3328 break;
3329 case spv::OpVectorTimesMatrix:
3330 assert(builder.isVector(left));
3331 assert(builder.isMatrix(right));
3332 break;
3333 case spv::OpMatrixTimesVector:
3334 assert(builder.isMatrix(left));
3335 assert(builder.isVector(right));
3336 break;
3337 case spv::OpMatrixTimesMatrix:
3338 assert(builder.isMatrix(left));
3339 assert(builder.isMatrix(right));
3340 break;
3341 default:
3342 firstClass = false;
3343 break;
3344 }
3345
qining25262b32016-05-06 17:25:16 -04003346 if (firstClass) {
3347 spv::Id result = builder.createBinOp(op, typeId, left, right);
3348 addDecoration(result, noContraction);
3349 return builder.setPrecision(result, precision);
3350 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003351
LoopDawg592860c2016-06-09 08:57:35 -06003352 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003353 // The result type of all of them is the same type as the (a) matrix operand.
3354 // The algorithm is to:
3355 // - break the matrix(es) into vectors
3356 // - smear any scalar to a vector
3357 // - do vector operations
3358 // - make a matrix out the vector results
3359 switch (op) {
3360 case spv::OpFAdd:
3361 case spv::OpFSub:
3362 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003363 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003364 case spv::OpFMul:
3365 {
3366 // one time set up...
3367 bool leftMat = builder.isMatrix(left);
3368 bool rightMat = builder.isMatrix(right);
3369 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3370 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3371 spv::Id scalarType = builder.getScalarTypeId(typeId);
3372 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3373 std::vector<spv::Id> results;
3374 spv::Id smearVec = spv::NoResult;
3375 if (builder.isScalar(left))
3376 smearVec = builder.smearScalar(precision, left, vecType);
3377 else if (builder.isScalar(right))
3378 smearVec = builder.smearScalar(precision, right, vecType);
3379
3380 // do each vector op
3381 for (unsigned int c = 0; c < numCols; ++c) {
3382 std::vector<unsigned int> indexes;
3383 indexes.push_back(c);
3384 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3385 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003386 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3387 addDecoration(result, noContraction);
3388 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003389 }
3390
3391 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003392 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003393 }
3394 default:
3395 assert(0);
3396 return spv::NoResult;
3397 }
3398}
3399
qining25262b32016-05-06 17:25:16 -04003400spv::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 -06003401{
3402 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003403 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003404 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003405 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003406#ifdef AMD_EXTENSIONS
3407 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3408#else
Rex Xu04db3f52015-09-16 11:44:02 +08003409 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003410#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003411
3412 switch (op) {
3413 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003414 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003415 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003416 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003417 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003418 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003419 unaryOp = spv::OpSNegate;
3420 break;
3421
3422 case glslang::EOpLogicalNot:
3423 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003424 unaryOp = spv::OpLogicalNot;
3425 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003426 case glslang::EOpBitwiseNot:
3427 unaryOp = spv::OpNot;
3428 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003429
John Kessenich140f3df2015-06-26 16:58:36 -06003430 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003431 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003432 break;
3433 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003434 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003435 break;
3436 case glslang::EOpTranspose:
3437 unaryOp = spv::OpTranspose;
3438 break;
3439
3440 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003441 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003442 break;
3443 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003444 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003445 break;
3446 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003447 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003448 break;
3449 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003450 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003451 break;
3452 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003453 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003454 break;
3455 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003456 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003457 break;
3458 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003459 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003460 break;
3461 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003462 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003463 break;
3464
3465 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003466 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003467 break;
3468 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003469 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003470 break;
3471 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003472 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003473 break;
3474 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003475 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003476 break;
3477 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003478 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003479 break;
3480 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003481 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003482 break;
3483
3484 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003485 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003486 break;
3487 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003488 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003489 break;
3490
3491 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003492 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003493 break;
3494 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003495 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003496 break;
3497 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003498 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003499 break;
3500 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003501 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003502 break;
3503 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003504 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003505 break;
3506 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003507 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003508 break;
3509
3510 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003511 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003512 break;
3513 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003514 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003515 break;
3516 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003517 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003518 break;
3519 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003520 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003521 break;
3522 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003523 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003524 break;
3525 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003526 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003527 break;
3528
3529 case glslang::EOpIsNan:
3530 unaryOp = spv::OpIsNan;
3531 break;
3532 case glslang::EOpIsInf:
3533 unaryOp = spv::OpIsInf;
3534 break;
LoopDawg592860c2016-06-09 08:57:35 -06003535 case glslang::EOpIsFinite:
3536 unaryOp = spv::OpIsFinite;
3537 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003538
Rex Xucbc426e2015-12-15 16:03:10 +08003539 case glslang::EOpFloatBitsToInt:
3540 case glslang::EOpFloatBitsToUint:
3541 case glslang::EOpIntBitsToFloat:
3542 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003543 case glslang::EOpDoubleBitsToInt64:
3544 case glslang::EOpDoubleBitsToUint64:
3545 case glslang::EOpInt64BitsToDouble:
3546 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003547 unaryOp = spv::OpBitcast;
3548 break;
3549
John Kessenich140f3df2015-06-26 16:58:36 -06003550 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003551 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003552 break;
3553 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003554 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003555 break;
3556 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003557 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003558 break;
3559 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003560 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003561 break;
3562 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003563 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003564 break;
3565 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003566 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003567 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003568 case glslang::EOpPackSnorm4x8:
3569 libCall = spv::GLSLstd450PackSnorm4x8;
3570 break;
3571 case glslang::EOpUnpackSnorm4x8:
3572 libCall = spv::GLSLstd450UnpackSnorm4x8;
3573 break;
3574 case glslang::EOpPackUnorm4x8:
3575 libCall = spv::GLSLstd450PackUnorm4x8;
3576 break;
3577 case glslang::EOpUnpackUnorm4x8:
3578 libCall = spv::GLSLstd450UnpackUnorm4x8;
3579 break;
3580 case glslang::EOpPackDouble2x32:
3581 libCall = spv::GLSLstd450PackDouble2x32;
3582 break;
3583 case glslang::EOpUnpackDouble2x32:
3584 libCall = spv::GLSLstd450UnpackDouble2x32;
3585 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003586
Rex Xu8ff43de2016-04-22 16:51:45 +08003587 case glslang::EOpPackInt2x32:
3588 case glslang::EOpUnpackInt2x32:
3589 case glslang::EOpPackUint2x32:
3590 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003591 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003592 break;
3593
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003594#ifdef AMD_EXTENSIONS
3595 case glslang::EOpPackFloat2x16:
3596 case glslang::EOpUnpackFloat2x16:
3597 unaryOp = spv::OpBitcast;
3598 break;
3599#endif
3600
John Kessenich140f3df2015-06-26 16:58:36 -06003601 case glslang::EOpDPdx:
3602 unaryOp = spv::OpDPdx;
3603 break;
3604 case glslang::EOpDPdy:
3605 unaryOp = spv::OpDPdy;
3606 break;
3607 case glslang::EOpFwidth:
3608 unaryOp = spv::OpFwidth;
3609 break;
3610 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003611 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003612 unaryOp = spv::OpDPdxFine;
3613 break;
3614 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003615 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003616 unaryOp = spv::OpDPdyFine;
3617 break;
3618 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003619 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003620 unaryOp = spv::OpFwidthFine;
3621 break;
3622 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003623 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003624 unaryOp = spv::OpDPdxCoarse;
3625 break;
3626 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003627 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003628 unaryOp = spv::OpDPdyCoarse;
3629 break;
3630 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003631 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003632 unaryOp = spv::OpFwidthCoarse;
3633 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003634 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003635 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003636 libCall = spv::GLSLstd450InterpolateAtCentroid;
3637 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003638 case glslang::EOpAny:
3639 unaryOp = spv::OpAny;
3640 break;
3641 case glslang::EOpAll:
3642 unaryOp = spv::OpAll;
3643 break;
3644
3645 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003646 if (isFloat)
3647 libCall = spv::GLSLstd450FAbs;
3648 else
3649 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003650 break;
3651 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003652 if (isFloat)
3653 libCall = spv::GLSLstd450FSign;
3654 else
3655 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003656 break;
3657
John Kessenichfc51d282015-08-19 13:34:18 -06003658 case glslang::EOpAtomicCounterIncrement:
3659 case glslang::EOpAtomicCounterDecrement:
3660 case glslang::EOpAtomicCounter:
3661 {
3662 // Handle all of the atomics in one place, in createAtomicOperation()
3663 std::vector<spv::Id> operands;
3664 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003665 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003666 }
3667
John Kessenichfc51d282015-08-19 13:34:18 -06003668 case glslang::EOpBitFieldReverse:
3669 unaryOp = spv::OpBitReverse;
3670 break;
3671 case glslang::EOpBitCount:
3672 unaryOp = spv::OpBitCount;
3673 break;
3674 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003675 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003676 break;
3677 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003678 if (isUnsigned)
3679 libCall = spv::GLSLstd450FindUMsb;
3680 else
3681 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003682 break;
3683
Rex Xu574ab042016-04-14 16:53:07 +08003684 case glslang::EOpBallot:
3685 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003686 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003687 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003688 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003689#ifdef AMD_EXTENSIONS
3690 case glslang::EOpMinInvocations:
3691 case glslang::EOpMaxInvocations:
3692 case glslang::EOpAddInvocations:
3693 case glslang::EOpMinInvocationsNonUniform:
3694 case glslang::EOpMaxInvocationsNonUniform:
3695 case glslang::EOpAddInvocationsNonUniform:
3696#endif
Rex Xu51596642016-09-21 18:56:12 +08003697 {
3698 std::vector<spv::Id> operands;
3699 operands.push_back(operand);
3700 return createInvocationsOperation(op, typeId, operands, typeProxy);
3701 }
Rex Xu9d93a232016-05-05 12:30:44 +08003702
3703#ifdef AMD_EXTENSIONS
3704 case glslang::EOpMbcnt:
3705 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3706 libCall = spv::MbcntAMD;
3707 break;
3708
3709 case glslang::EOpCubeFaceIndex:
3710 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3711 libCall = spv::CubeFaceIndexAMD;
3712 break;
3713
3714 case glslang::EOpCubeFaceCoord:
3715 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3716 libCall = spv::CubeFaceCoordAMD;
3717 break;
3718#endif
Rex Xu338b1852016-05-05 20:38:33 +08003719
John Kessenich140f3df2015-06-26 16:58:36 -06003720 default:
3721 return 0;
3722 }
3723
3724 spv::Id id;
3725 if (libCall >= 0) {
3726 std::vector<spv::Id> args;
3727 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003728 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003729 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003730 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003731 }
John Kessenich140f3df2015-06-26 16:58:36 -06003732
qining25262b32016-05-06 17:25:16 -04003733 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003734 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003735}
3736
John Kessenich7a53f762016-01-20 11:19:27 -07003737// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003738spv::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 -07003739{
3740 // Handle unary operations vector by vector.
3741 // The result type is the same type as the original type.
3742 // The algorithm is to:
3743 // - break the matrix into vectors
3744 // - apply the operation to each vector
3745 // - make a matrix out the vector results
3746
3747 // get the types sorted out
3748 int numCols = builder.getNumColumns(operand);
3749 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003750 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3751 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003752 std::vector<spv::Id> results;
3753
3754 // do each vector op
3755 for (int c = 0; c < numCols; ++c) {
3756 std::vector<unsigned int> indexes;
3757 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003758 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3759 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3760 addDecoration(destVec, noContraction);
3761 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003762 }
3763
3764 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003765 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003766}
3767
Rex Xu73e3ce72016-04-27 18:48:17 +08003768spv::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 -06003769{
3770 spv::Op convOp = spv::OpNop;
3771 spv::Id zero = 0;
3772 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003773 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003774
3775 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3776
3777 switch (op) {
3778 case glslang::EOpConvIntToBool:
3779 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003780 case glslang::EOpConvInt64ToBool:
3781 case glslang::EOpConvUint64ToBool:
3782 zero = (op == glslang::EOpConvInt64ToBool ||
3783 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003784 zero = makeSmearedConstant(zero, vectorSize);
3785 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3786
3787 case glslang::EOpConvFloatToBool:
3788 zero = builder.makeFloatConstant(0.0F);
3789 zero = makeSmearedConstant(zero, vectorSize);
3790 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3791
3792 case glslang::EOpConvDoubleToBool:
3793 zero = builder.makeDoubleConstant(0.0);
3794 zero = makeSmearedConstant(zero, vectorSize);
3795 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3796
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003797#ifdef AMD_EXTENSIONS
3798 case glslang::EOpConvFloat16ToBool:
3799 zero = builder.makeFloat16Constant(0.0F);
3800 zero = makeSmearedConstant(zero, vectorSize);
3801 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3802#endif
3803
John Kessenich140f3df2015-06-26 16:58:36 -06003804 case glslang::EOpConvBoolToFloat:
3805 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003806 zero = builder.makeFloatConstant(0.0F);
3807 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06003808 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003809
John Kessenich140f3df2015-06-26 16:58:36 -06003810 case glslang::EOpConvBoolToDouble:
3811 convOp = spv::OpSelect;
3812 zero = builder.makeDoubleConstant(0.0);
3813 one = builder.makeDoubleConstant(1.0);
3814 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003815
3816#ifdef AMD_EXTENSIONS
3817 case glslang::EOpConvBoolToFloat16:
3818 convOp = spv::OpSelect;
3819 zero = builder.makeFloat16Constant(0.0F);
3820 one = builder.makeFloat16Constant(1.0F);
3821 break;
3822#endif
3823
John Kessenich140f3df2015-06-26 16:58:36 -06003824 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003825 case glslang::EOpConvBoolToInt64:
3826 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3827 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003828 convOp = spv::OpSelect;
3829 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003830
John Kessenich140f3df2015-06-26 16:58:36 -06003831 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003832 case glslang::EOpConvBoolToUint64:
3833 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3834 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003835 convOp = spv::OpSelect;
3836 break;
3837
3838 case glslang::EOpConvIntToFloat:
3839 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003840 case glslang::EOpConvInt64ToFloat:
3841 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003842#ifdef AMD_EXTENSIONS
3843 case glslang::EOpConvIntToFloat16:
3844 case glslang::EOpConvInt64ToFloat16:
3845#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003846 convOp = spv::OpConvertSToF;
3847 break;
3848
3849 case glslang::EOpConvUintToFloat:
3850 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003851 case glslang::EOpConvUint64ToFloat:
3852 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003853#ifdef AMD_EXTENSIONS
3854 case glslang::EOpConvUintToFloat16:
3855 case glslang::EOpConvUint64ToFloat16:
3856#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003857 convOp = spv::OpConvertUToF;
3858 break;
3859
3860 case glslang::EOpConvDoubleToFloat:
3861 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003862#ifdef AMD_EXTENSIONS
3863 case glslang::EOpConvDoubleToFloat16:
3864 case glslang::EOpConvFloat16ToDouble:
3865 case glslang::EOpConvFloatToFloat16:
3866 case glslang::EOpConvFloat16ToFloat:
3867#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003868 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003869 if (builder.isMatrixType(destType))
3870 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003871 break;
3872
3873 case glslang::EOpConvFloatToInt:
3874 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003875 case glslang::EOpConvFloatToInt64:
3876 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003877#ifdef AMD_EXTENSIONS
3878 case glslang::EOpConvFloat16ToInt:
3879 case glslang::EOpConvFloat16ToInt64:
3880#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003881 convOp = spv::OpConvertFToS;
3882 break;
3883
3884 case glslang::EOpConvUintToInt:
3885 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003886 case glslang::EOpConvUint64ToInt64:
3887 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003888 if (builder.isInSpecConstCodeGenMode()) {
3889 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08003890 zero = (op == glslang::EOpConvUint64ToInt64 ||
3891 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003892 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003893 // Use OpIAdd, instead of OpBitcast to do the conversion when
3894 // generating for OpSpecConstantOp instruction.
3895 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3896 }
3897 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003898 convOp = spv::OpBitcast;
3899 break;
3900
3901 case glslang::EOpConvFloatToUint:
3902 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003903 case glslang::EOpConvFloatToUint64:
3904 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003905#ifdef AMD_EXTENSIONS
3906 case glslang::EOpConvFloat16ToUint:
3907 case glslang::EOpConvFloat16ToUint64:
3908#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003909 convOp = spv::OpConvertFToU;
3910 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003911
3912 case glslang::EOpConvIntToInt64:
3913 case glslang::EOpConvInt64ToInt:
3914 convOp = spv::OpSConvert;
3915 break;
3916
3917 case glslang::EOpConvUintToUint64:
3918 case glslang::EOpConvUint64ToUint:
3919 convOp = spv::OpUConvert;
3920 break;
3921
3922 case glslang::EOpConvIntToUint64:
3923 case glslang::EOpConvInt64ToUint:
3924 case glslang::EOpConvUint64ToInt:
3925 case glslang::EOpConvUintToInt64:
3926 // OpSConvert/OpUConvert + OpBitCast
3927 switch (op) {
3928 case glslang::EOpConvIntToUint64:
3929 convOp = spv::OpSConvert;
3930 type = builder.makeIntType(64);
3931 break;
3932 case glslang::EOpConvInt64ToUint:
3933 convOp = spv::OpSConvert;
3934 type = builder.makeIntType(32);
3935 break;
3936 case glslang::EOpConvUint64ToInt:
3937 convOp = spv::OpUConvert;
3938 type = builder.makeUintType(32);
3939 break;
3940 case glslang::EOpConvUintToInt64:
3941 convOp = spv::OpUConvert;
3942 type = builder.makeUintType(64);
3943 break;
3944 default:
3945 assert(0);
3946 break;
3947 }
3948
3949 if (vectorSize > 0)
3950 type = builder.makeVectorType(type, vectorSize);
3951
3952 operand = builder.createUnaryOp(convOp, type, operand);
3953
3954 if (builder.isInSpecConstCodeGenMode()) {
3955 // Build zero scalar or vector for OpIAdd.
3956 zero = (op == glslang::EOpConvIntToUint64 ||
3957 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3958 zero = makeSmearedConstant(zero, vectorSize);
3959 // Use OpIAdd, instead of OpBitcast to do the conversion when
3960 // generating for OpSpecConstantOp instruction.
3961 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3962 }
3963 // For normal run-time conversion instruction, use OpBitcast.
3964 convOp = spv::OpBitcast;
3965 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003966 default:
3967 break;
3968 }
3969
3970 spv::Id result = 0;
3971 if (convOp == spv::OpNop)
3972 return result;
3973
3974 if (convOp == spv::OpSelect) {
3975 zero = makeSmearedConstant(zero, vectorSize);
3976 one = makeSmearedConstant(one, vectorSize);
3977 result = builder.createTriOp(convOp, destType, operand, one, zero);
3978 } else
3979 result = builder.createUnaryOp(convOp, destType, operand);
3980
John Kessenich32cfd492016-02-02 12:37:46 -07003981 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003982}
3983
3984spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3985{
3986 if (vectorSize == 0)
3987 return constant;
3988
3989 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3990 std::vector<spv::Id> components;
3991 for (int c = 0; c < vectorSize; ++c)
3992 components.push_back(constant);
3993 return builder.makeCompositeConstant(vectorTypeId, components);
3994}
3995
John Kessenich426394d2015-07-23 10:22:48 -06003996// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003997spv::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 -06003998{
3999 spv::Op opCode = spv::OpNop;
4000
4001 switch (op) {
4002 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004003 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004004 opCode = spv::OpAtomicIAdd;
4005 break;
4006 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004007 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004008 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004009 break;
4010 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004011 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004012 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004013 break;
4014 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004015 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004016 opCode = spv::OpAtomicAnd;
4017 break;
4018 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004019 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004020 opCode = spv::OpAtomicOr;
4021 break;
4022 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004023 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004024 opCode = spv::OpAtomicXor;
4025 break;
4026 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004027 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004028 opCode = spv::OpAtomicExchange;
4029 break;
4030 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004031 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004032 opCode = spv::OpAtomicCompareExchange;
4033 break;
4034 case glslang::EOpAtomicCounterIncrement:
4035 opCode = spv::OpAtomicIIncrement;
4036 break;
4037 case glslang::EOpAtomicCounterDecrement:
4038 opCode = spv::OpAtomicIDecrement;
4039 break;
4040 case glslang::EOpAtomicCounter:
4041 opCode = spv::OpAtomicLoad;
4042 break;
4043 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004044 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004045 break;
4046 }
4047
4048 // Sort out the operands
4049 // - mapping from glslang -> SPV
4050 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004051 // - compare-exchange swaps the value and comparator
4052 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004053 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4054 auto opIt = operands.begin(); // walk the glslang operands
4055 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004056 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4057 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4058 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004059 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4060 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004061 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004062 spvAtomicOperands.push_back(*(opIt + 1));
4063 spvAtomicOperands.push_back(*opIt);
4064 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004065 }
John Kessenich426394d2015-07-23 10:22:48 -06004066
John Kessenich3e60a6f2015-09-14 22:45:16 -06004067 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004068 for (; opIt != operands.end(); ++opIt)
4069 spvAtomicOperands.push_back(*opIt);
4070
4071 return builder.createOp(opCode, typeId, spvAtomicOperands);
4072}
4073
John Kessenich91cef522016-05-05 16:45:40 -06004074// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004075spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004076{
Rex Xu9d93a232016-05-05 12:30:44 +08004077 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004078#ifdef AMD_EXTENSIONS
4079 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4080#else
Rex Xu9d93a232016-05-05 12:30:44 +08004081 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004082#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004083
Rex Xu51596642016-09-21 18:56:12 +08004084 spv::Op opCode = spv::OpNop;
John Kessenich91cef522016-05-05 16:45:40 -06004085
Rex Xu51596642016-09-21 18:56:12 +08004086 std::vector<spv::Id> spvGroupOperands;
4087 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation) {
4088 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4089 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
4090 } else {
4091 builder.addCapability(spv::CapabilityGroups);
4092
4093 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004094#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +08004095 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
4096 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
4097 spvGroupOperands.push_back(spv::GroupOperationReduce);
Rex Xu9d93a232016-05-05 12:30:44 +08004098#endif
Rex Xu51596642016-09-21 18:56:12 +08004099 }
4100
4101 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4102 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004103
4104 switch (op) {
4105 case glslang::EOpAnyInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004106 opCode = spv::OpGroupAny;
4107 break;
John Kessenich91cef522016-05-05 16:45:40 -06004108 case glslang::EOpAllInvocations:
Rex Xu51596642016-09-21 18:56:12 +08004109 opCode = spv::OpGroupAll;
4110 break;
John Kessenich91cef522016-05-05 16:45:40 -06004111 case glslang::EOpAllInvocationsEqual:
4112 {
Rex Xu51596642016-09-21 18:56:12 +08004113 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, spvGroupOperands);
4114 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004115
4116 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
4117 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
4118 }
Rex Xu51596642016-09-21 18:56:12 +08004119
4120 case glslang::EOpReadInvocation:
4121 opCode = spv::OpGroupBroadcast;
Rex Xub7072052016-09-26 15:53:40 +08004122 if (builder.isVectorType(typeId))
4123 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004124 break;
4125 case glslang::EOpReadFirstInvocation:
4126 opCode = spv::OpSubgroupFirstInvocationKHR;
4127 break;
4128 case glslang::EOpBallot:
4129 {
4130 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4131 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4132 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4133 //
4134 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4135 //
4136 spv::Id uintType = builder.makeUintType(32);
4137 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4138 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4139
4140 std::vector<spv::Id> components;
4141 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4142 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4143
4144 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4145 return builder.createUnaryOp(spv::OpBitcast, typeId,
4146 builder.createCompositeConstruct(uvec2Type, components));
4147 }
4148
Rex Xu9d93a232016-05-05 12:30:44 +08004149#ifdef AMD_EXTENSIONS
4150 case glslang::EOpMinInvocations:
4151 case glslang::EOpMaxInvocations:
4152 case glslang::EOpAddInvocations:
Rex Xu9d93a232016-05-05 12:30:44 +08004153 if (op == glslang::EOpMinInvocations) {
4154 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004155 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004156 else {
4157 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004158 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004159 else
Rex Xu51596642016-09-21 18:56:12 +08004160 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004161 }
4162 } else if (op == glslang::EOpMaxInvocations) {
4163 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004164 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004165 else {
4166 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004167 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004168 else
Rex Xu51596642016-09-21 18:56:12 +08004169 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004170 }
4171 } else {
4172 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004173 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004174 else
Rex Xu51596642016-09-21 18:56:12 +08004175 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004176 }
4177
Rex Xu2bbbe062016-08-23 15:41:05 +08004178 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004179 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004180
4181 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004182 case glslang::EOpMinInvocationsNonUniform:
4183 case glslang::EOpMaxInvocationsNonUniform:
4184 case glslang::EOpAddInvocationsNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004185 if (op == glslang::EOpMinInvocationsNonUniform) {
4186 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004187 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004188 else {
4189 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004190 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004191 else
Rex Xu51596642016-09-21 18:56:12 +08004192 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004193 }
4194 }
4195 else if (op == glslang::EOpMaxInvocationsNonUniform) {
4196 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004197 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004198 else {
4199 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004200 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004201 else
Rex Xu51596642016-09-21 18:56:12 +08004202 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004203 }
4204 }
4205 else {
4206 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004207 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004208 else
Rex Xu51596642016-09-21 18:56:12 +08004209 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004210 }
4211
Rex Xu2bbbe062016-08-23 15:41:05 +08004212 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004213 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004214
4215 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004216#endif
John Kessenich91cef522016-05-05 16:45:40 -06004217 default:
4218 logger->missingFunctionality("invocation operation");
4219 return spv::NoResult;
4220 }
Rex Xu51596642016-09-21 18:56:12 +08004221
4222 assert(opCode != spv::OpNop);
4223 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004224}
4225
Rex Xu2bbbe062016-08-23 15:41:05 +08004226// Create group invocation operations on a vector
Rex Xub7072052016-09-26 15:53:40 +08004227spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004228{
Rex Xub7072052016-09-26 15:53:40 +08004229#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004230 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4231 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004232 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004233 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4234 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4235 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004236#else
4237 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4238 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
4239 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast);
4240#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004241
4242 // Handle group invocation operations scalar by scalar.
4243 // The result type is the same type as the original type.
4244 // The algorithm is to:
4245 // - break the vector into scalars
4246 // - apply the operation to each scalar
4247 // - make a vector out the scalar results
4248
4249 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004250 int numComponents = builder.getNumComponents(operands[0]);
4251 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004252 std::vector<spv::Id> results;
4253
4254 // do each scalar op
4255 for (int comp = 0; comp < numComponents; ++comp) {
4256 std::vector<unsigned int> indexes;
4257 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004258 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xu2bbbe062016-08-23 15:41:05 +08004259
Rex Xub7072052016-09-26 15:53:40 +08004260 std::vector<spv::Id> spvGroupOperands;
4261 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
4262 if (op == spv::OpGroupBroadcast) {
4263 spvGroupOperands.push_back(scalar);
4264 spvGroupOperands.push_back(operands[1]);
4265 } else {
4266 spvGroupOperands.push_back(spv::GroupOperationReduce);
4267 spvGroupOperands.push_back(scalar);
4268 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004269
Rex Xub7072052016-09-26 15:53:40 +08004270 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004271 }
4272
4273 // put the pieces together
4274 return builder.createCompositeConstruct(typeId, results);
4275}
Rex Xu2bbbe062016-08-23 15:41:05 +08004276
John Kessenich5e4b1242015-08-06 22:53:06 -06004277spv::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 -06004278{
Rex Xu8ff43de2016-04-22 16:51:45 +08004279 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004280#ifdef AMD_EXTENSIONS
4281 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4282#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004283 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004284#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004285
John Kessenich140f3df2015-06-26 16:58:36 -06004286 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004287 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004288 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004289 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004290 spv::Id typeId0 = 0;
4291 if (consumedOperands > 0)
4292 typeId0 = builder.getTypeId(operands[0]);
4293 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004294
4295 switch (op) {
4296 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004297 if (isFloat)
4298 libCall = spv::GLSLstd450FMin;
4299 else if (isUnsigned)
4300 libCall = spv::GLSLstd450UMin;
4301 else
4302 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004303 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004304 break;
4305 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004306 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004307 break;
4308 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004309 if (isFloat)
4310 libCall = spv::GLSLstd450FMax;
4311 else if (isUnsigned)
4312 libCall = spv::GLSLstd450UMax;
4313 else
4314 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004315 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004316 break;
4317 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004318 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004319 break;
4320 case glslang::EOpDot:
4321 opCode = spv::OpDot;
4322 break;
4323 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004324 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004325 break;
4326
4327 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004328 if (isFloat)
4329 libCall = spv::GLSLstd450FClamp;
4330 else if (isUnsigned)
4331 libCall = spv::GLSLstd450UClamp;
4332 else
4333 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004334 builder.promoteScalar(precision, operands.front(), operands[1]);
4335 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004336 break;
4337 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004338 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4339 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004340 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004341 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004342 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004343 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004344 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004345 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004346 break;
4347 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004348 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004349 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004350 break;
4351 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004352 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004353 builder.promoteScalar(precision, operands[0], operands[2]);
4354 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004355 break;
4356
4357 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004358 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004359 break;
4360 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004361 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004362 break;
4363 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004364 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004365 break;
4366 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004367 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004368 break;
4369 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004370 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004371 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004372 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004373 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004374 libCall = spv::GLSLstd450InterpolateAtSample;
4375 break;
4376 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004377 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004378 libCall = spv::GLSLstd450InterpolateAtOffset;
4379 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004380 case glslang::EOpAddCarry:
4381 opCode = spv::OpIAddCarry;
4382 typeId = builder.makeStructResultType(typeId0, typeId0);
4383 consumedOperands = 2;
4384 break;
4385 case glslang::EOpSubBorrow:
4386 opCode = spv::OpISubBorrow;
4387 typeId = builder.makeStructResultType(typeId0, typeId0);
4388 consumedOperands = 2;
4389 break;
4390 case glslang::EOpUMulExtended:
4391 opCode = spv::OpUMulExtended;
4392 typeId = builder.makeStructResultType(typeId0, typeId0);
4393 consumedOperands = 2;
4394 break;
4395 case glslang::EOpIMulExtended:
4396 opCode = spv::OpSMulExtended;
4397 typeId = builder.makeStructResultType(typeId0, typeId0);
4398 consumedOperands = 2;
4399 break;
4400 case glslang::EOpBitfieldExtract:
4401 if (isUnsigned)
4402 opCode = spv::OpBitFieldUExtract;
4403 else
4404 opCode = spv::OpBitFieldSExtract;
4405 break;
4406 case glslang::EOpBitfieldInsert:
4407 opCode = spv::OpBitFieldInsert;
4408 break;
4409
4410 case glslang::EOpFma:
4411 libCall = spv::GLSLstd450Fma;
4412 break;
4413 case glslang::EOpFrexp:
4414 libCall = spv::GLSLstd450FrexpStruct;
4415 if (builder.getNumComponents(operands[0]) == 1)
4416 frexpIntType = builder.makeIntegerType(32, true);
4417 else
4418 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4419 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4420 consumedOperands = 1;
4421 break;
4422 case glslang::EOpLdexp:
4423 libCall = spv::GLSLstd450Ldexp;
4424 break;
4425
Rex Xu574ab042016-04-14 16:53:07 +08004426 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004427 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004428
Rex Xu9d93a232016-05-05 12:30:44 +08004429#ifdef AMD_EXTENSIONS
4430 case glslang::EOpSwizzleInvocations:
4431 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4432 libCall = spv::SwizzleInvocationsAMD;
4433 break;
4434 case glslang::EOpSwizzleInvocationsMasked:
4435 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4436 libCall = spv::SwizzleInvocationsMaskedAMD;
4437 break;
4438 case glslang::EOpWriteInvocation:
4439 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4440 libCall = spv::WriteInvocationAMD;
4441 break;
4442
4443 case glslang::EOpMin3:
4444 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4445 if (isFloat)
4446 libCall = spv::FMin3AMD;
4447 else {
4448 if (isUnsigned)
4449 libCall = spv::UMin3AMD;
4450 else
4451 libCall = spv::SMin3AMD;
4452 }
4453 break;
4454 case glslang::EOpMax3:
4455 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4456 if (isFloat)
4457 libCall = spv::FMax3AMD;
4458 else {
4459 if (isUnsigned)
4460 libCall = spv::UMax3AMD;
4461 else
4462 libCall = spv::SMax3AMD;
4463 }
4464 break;
4465 case glslang::EOpMid3:
4466 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4467 if (isFloat)
4468 libCall = spv::FMid3AMD;
4469 else {
4470 if (isUnsigned)
4471 libCall = spv::UMid3AMD;
4472 else
4473 libCall = spv::SMid3AMD;
4474 }
4475 break;
4476
4477 case glslang::EOpInterpolateAtVertex:
4478 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4479 libCall = spv::InterpolateAtVertexAMD;
4480 break;
4481#endif
4482
John Kessenich140f3df2015-06-26 16:58:36 -06004483 default:
4484 return 0;
4485 }
4486
4487 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004488 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004489 // Use an extended instruction from the standard library.
4490 // Construct the call arguments, without modifying the original operands vector.
4491 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4492 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004493 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004494 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004495 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004496 case 0:
4497 // should all be handled by visitAggregate and createNoArgOperation
4498 assert(0);
4499 return 0;
4500 case 1:
4501 // should all be handled by createUnaryOperation
4502 assert(0);
4503 return 0;
4504 case 2:
4505 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4506 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004507 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004508 // anything 3 or over doesn't have l-value operands, so all should be consumed
4509 assert(consumedOperands == operands.size());
4510 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004511 break;
4512 }
4513 }
4514
John Kessenich55e7d112015-11-15 21:33:39 -07004515 // Decode the return types that were structures
4516 switch (op) {
4517 case glslang::EOpAddCarry:
4518 case glslang::EOpSubBorrow:
4519 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4520 id = builder.createCompositeExtract(id, typeId0, 0);
4521 break;
4522 case glslang::EOpUMulExtended:
4523 case glslang::EOpIMulExtended:
4524 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4525 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4526 break;
4527 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004528 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004529 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4530 id = builder.createCompositeExtract(id, typeId0, 0);
4531 break;
4532 default:
4533 break;
4534 }
4535
John Kessenich32cfd492016-02-02 12:37:46 -07004536 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004537}
4538
Rex Xu9d93a232016-05-05 12:30:44 +08004539// Intrinsics with no arguments (or no return value, and no precision).
4540spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004541{
4542 // TODO: get the barrier operands correct
4543
4544 switch (op) {
4545 case glslang::EOpEmitVertex:
4546 builder.createNoResultOp(spv::OpEmitVertex);
4547 return 0;
4548 case glslang::EOpEndPrimitive:
4549 builder.createNoResultOp(spv::OpEndPrimitive);
4550 return 0;
4551 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004552 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004553 return 0;
4554 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004555 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004556 return 0;
4557 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004558 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004559 return 0;
4560 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004561 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004562 return 0;
4563 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004564 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004565 return 0;
4566 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004567 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004568 return 0;
4569 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004570 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004571 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004572 case glslang::EOpAllMemoryBarrierWithGroupSync:
4573 // Control barrier with non-"None" semantic is also a memory barrier.
4574 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4575 return 0;
4576 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4577 // Control barrier with non-"None" semantic is also a memory barrier.
4578 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4579 return 0;
4580 case glslang::EOpWorkgroupMemoryBarrier:
4581 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4582 return 0;
4583 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4584 // Control barrier with non-"None" semantic is also a memory barrier.
4585 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4586 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004587#ifdef AMD_EXTENSIONS
4588 case glslang::EOpTime:
4589 {
4590 std::vector<spv::Id> args; // Dummy arguments
4591 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4592 return builder.setPrecision(id, precision);
4593 }
4594#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004595 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004596 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004597 return 0;
4598 }
4599}
4600
4601spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4602{
John Kessenich2f273362015-07-18 22:34:27 -06004603 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004604 spv::Id id;
4605 if (symbolValues.end() != iter) {
4606 id = iter->second;
4607 return id;
4608 }
4609
4610 // it was not found, create it
4611 id = createSpvVariable(symbol);
4612 symbolValues[symbol->getId()] = id;
4613
Rex Xuc884b4a2016-06-29 15:03:44 +08004614 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004615 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004616 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004617 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004618 if (symbol->getType().getQualifier().hasSpecConstantId())
4619 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004620 if (symbol->getQualifier().hasIndex())
4621 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4622 if (symbol->getQualifier().hasComponent())
4623 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4624 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004625 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004626 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004627 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004628 if (symbol->getQualifier().hasXfbBuffer())
4629 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4630 if (symbol->getQualifier().hasXfbOffset())
4631 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4632 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004633 // atomic counters use this:
4634 if (symbol->getQualifier().hasOffset())
4635 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004636 }
4637
scygan2c864272016-05-18 18:09:17 +02004638 if (symbol->getQualifier().hasLocation())
4639 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004640 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004641 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004642 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004643 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004644 }
John Kessenich140f3df2015-06-26 16:58:36 -06004645 if (symbol->getQualifier().hasSet())
4646 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004647 else if (IsDescriptorResource(symbol->getType())) {
4648 // default to 0
4649 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4650 }
John Kessenich140f3df2015-06-26 16:58:36 -06004651 if (symbol->getQualifier().hasBinding())
4652 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004653 if (symbol->getQualifier().hasAttachment())
4654 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004655 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004656 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004657 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004658 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004659 if (symbol->getQualifier().hasXfbBuffer())
4660 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4661 }
4662
Rex Xu1da878f2016-02-21 20:59:01 +08004663 if (symbol->getType().isImage()) {
4664 std::vector<spv::Decoration> memory;
4665 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4666 for (unsigned int i = 0; i < memory.size(); ++i)
4667 addDecoration(id, memory[i]);
4668 }
4669
John Kessenich140f3df2015-06-26 16:58:36 -06004670 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004671 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004672 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004673 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004674
John Kessenich140f3df2015-06-26 16:58:36 -06004675 return id;
4676}
4677
John Kessenich55e7d112015-11-15 21:33:39 -07004678// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004679void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4680{
John Kessenich4016e382016-07-15 11:53:56 -06004681 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004682 builder.addDecoration(id, dec);
4683}
4684
John Kessenich55e7d112015-11-15 21:33:39 -07004685// If 'dec' is valid, add a one-operand decoration to an object
4686void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4687{
John Kessenich4016e382016-07-15 11:53:56 -06004688 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004689 builder.addDecoration(id, dec, value);
4690}
4691
4692// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004693void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4694{
John Kessenich4016e382016-07-15 11:53:56 -06004695 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004696 builder.addMemberDecoration(id, (unsigned)member, dec);
4697}
4698
John Kessenich92187592016-02-01 13:45:25 -07004699// If 'dec' is valid, add a one-operand decoration to a struct member
4700void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4701{
John Kessenich4016e382016-07-15 11:53:56 -06004702 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004703 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4704}
4705
John Kessenich55e7d112015-11-15 21:33:39 -07004706// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004707// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004708//
4709// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4710//
4711// Recursively walk the nodes. The nodes form a tree whose leaves are
4712// regular constants, which themselves are trees that createSpvConstant()
4713// recursively walks. So, this function walks the "top" of the tree:
4714// - emit specialization constant-building instructions for specConstant
4715// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004716spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004717{
John Kessenich7cc0e282016-03-20 00:46:02 -06004718 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004719
qining4f4bb812016-04-03 23:55:17 -04004720 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004721 if (! node.getQualifier().specConstant) {
4722 // hand off to the non-spec-constant path
4723 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4724 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004725 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004726 nextConst, false);
4727 }
4728
4729 // We now know we have a specialization constant to build
4730
John Kessenichd94c0032016-05-30 19:29:40 -06004731 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004732 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4733 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4734 std::vector<spv::Id> dimConstId;
4735 for (int dim = 0; dim < 3; ++dim) {
4736 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4737 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4738 if (specConst)
4739 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4740 }
4741 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4742 }
4743
4744 // An AST node labelled as specialization constant should be a symbol node.
4745 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4746 if (auto* sn = node.getAsSymbolNode()) {
4747 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004748 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4749 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4750 // will set the builder into spec constant op instruction generating mode.
4751 sub_tree->traverse(this);
4752 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004753 } else if (auto* const_union_array = &sn->getConstArray()){
4754 int nextConst = 0;
4755 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004756 }
4757 }
qining4f4bb812016-04-03 23:55:17 -04004758
4759 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4760 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004761 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004762 exit(1);
4763 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004764}
4765
John Kessenich140f3df2015-06-26 16:58:36 -06004766// Use 'consts' as the flattened glslang source of scalar constants to recursively
4767// build the aggregate SPIR-V constant.
4768//
4769// If there are not enough elements present in 'consts', 0 will be substituted;
4770// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4771//
qining08408382016-03-21 09:51:37 -04004772spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004773{
4774 // vector of constants for SPIR-V
4775 std::vector<spv::Id> spvConsts;
4776
4777 // Type is used for struct and array constants
4778 spv::Id typeId = convertGlslangToSpvType(glslangType);
4779
4780 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004781 glslang::TType elementType(glslangType, 0);
4782 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004783 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004784 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004785 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004786 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004787 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004788 } else if (glslangType.getStruct()) {
4789 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4790 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004791 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004792 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004793 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4794 bool zero = nextConst >= consts.size();
4795 switch (glslangType.getBasicType()) {
4796 case glslang::EbtInt:
4797 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4798 break;
4799 case glslang::EbtUint:
4800 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4801 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004802 case glslang::EbtInt64:
4803 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4804 break;
4805 case glslang::EbtUint64:
4806 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4807 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004808 case glslang::EbtFloat:
4809 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4810 break;
4811 case glslang::EbtDouble:
4812 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4813 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004814#ifdef AMD_EXTENSIONS
4815 case glslang::EbtFloat16:
4816 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4817 break;
4818#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004819 case glslang::EbtBool:
4820 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4821 break;
4822 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004823 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004824 break;
4825 }
4826 ++nextConst;
4827 }
4828 } else {
4829 // we have a non-aggregate (scalar) constant
4830 bool zero = nextConst >= consts.size();
4831 spv::Id scalar = 0;
4832 switch (glslangType.getBasicType()) {
4833 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004834 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004835 break;
4836 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004837 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004838 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004839 case glslang::EbtInt64:
4840 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4841 break;
4842 case glslang::EbtUint64:
4843 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4844 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004845 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004846 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004847 break;
4848 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004849 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004850 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004851#ifdef AMD_EXTENSIONS
4852 case glslang::EbtFloat16:
4853 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
4854 break;
4855#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004856 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004857 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004858 break;
4859 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004860 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004861 break;
4862 }
4863 ++nextConst;
4864 return scalar;
4865 }
4866
4867 return builder.makeCompositeConstant(typeId, spvConsts);
4868}
4869
John Kessenich7c1aa102015-10-15 13:29:11 -06004870// Return true if the node is a constant or symbol whose reading has no
4871// non-trivial observable cost or effect.
4872bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4873{
4874 // don't know what this is
4875 if (node == nullptr)
4876 return false;
4877
4878 // a constant is safe
4879 if (node->getAsConstantUnion() != nullptr)
4880 return true;
4881
4882 // not a symbol means non-trivial
4883 if (node->getAsSymbolNode() == nullptr)
4884 return false;
4885
4886 // a symbol, depends on what's being read
4887 switch (node->getType().getQualifier().storage) {
4888 case glslang::EvqTemporary:
4889 case glslang::EvqGlobal:
4890 case glslang::EvqIn:
4891 case glslang::EvqInOut:
4892 case glslang::EvqConst:
4893 case glslang::EvqConstReadOnly:
4894 case glslang::EvqUniform:
4895 return true;
4896 default:
4897 return false;
4898 }
qining25262b32016-05-06 17:25:16 -04004899}
John Kessenich7c1aa102015-10-15 13:29:11 -06004900
4901// A node is trivial if it is a single operation with no side effects.
4902// Error on the side of saying non-trivial.
4903// Return true if trivial.
4904bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4905{
4906 if (node == nullptr)
4907 return false;
4908
4909 // symbols and constants are trivial
4910 if (isTrivialLeaf(node))
4911 return true;
4912
4913 // otherwise, it needs to be a simple operation or one or two leaf nodes
4914
4915 // not a simple operation
4916 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4917 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4918 if (binaryNode == nullptr && unaryNode == nullptr)
4919 return false;
4920
4921 // not on leaf nodes
4922 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4923 return false;
4924
4925 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4926 return false;
4927 }
4928
4929 switch (node->getAsOperator()->getOp()) {
4930 case glslang::EOpLogicalNot:
4931 case glslang::EOpConvIntToBool:
4932 case glslang::EOpConvUintToBool:
4933 case glslang::EOpConvFloatToBool:
4934 case glslang::EOpConvDoubleToBool:
4935 case glslang::EOpEqual:
4936 case glslang::EOpNotEqual:
4937 case glslang::EOpLessThan:
4938 case glslang::EOpGreaterThan:
4939 case glslang::EOpLessThanEqual:
4940 case glslang::EOpGreaterThanEqual:
4941 case glslang::EOpIndexDirect:
4942 case glslang::EOpIndexDirectStruct:
4943 case glslang::EOpLogicalXor:
4944 case glslang::EOpAny:
4945 case glslang::EOpAll:
4946 return true;
4947 default:
4948 return false;
4949 }
4950}
4951
4952// Emit short-circuiting code, where 'right' is never evaluated unless
4953// the left side is true (for &&) or false (for ||).
4954spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4955{
4956 spv::Id boolTypeId = builder.makeBoolType();
4957
4958 // emit left operand
4959 builder.clearAccessChain();
4960 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004961 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004962
4963 // Operands to accumulate OpPhi operands
4964 std::vector<spv::Id> phiOperands;
4965 // accumulate left operand's phi information
4966 phiOperands.push_back(leftId);
4967 phiOperands.push_back(builder.getBuildPoint()->getId());
4968
4969 // Make the two kinds of operation symmetric with a "!"
4970 // || => emit "if (! left) result = right"
4971 // && => emit "if ( left) result = right"
4972 //
4973 // TODO: this runtime "not" for || could be avoided by adding functionality
4974 // to 'builder' to have an "else" without an "then"
4975 if (op == glslang::EOpLogicalOr)
4976 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4977
4978 // make an "if" based on the left value
4979 spv::Builder::If ifBuilder(leftId, builder);
4980
4981 // emit right operand as the "then" part of the "if"
4982 builder.clearAccessChain();
4983 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004984 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004985
4986 // accumulate left operand's phi information
4987 phiOperands.push_back(rightId);
4988 phiOperands.push_back(builder.getBuildPoint()->getId());
4989
4990 // finish the "if"
4991 ifBuilder.makeEndIf();
4992
4993 // phi together the two results
4994 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4995}
4996
Rex Xu9d93a232016-05-05 12:30:44 +08004997// Return type Id of the imported set of extended instructions corresponds to the name.
4998// Import this set if it has not been imported yet.
4999spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5000{
5001 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5002 return extBuiltinMap[name];
5003 else {
Rex Xu51596642016-09-21 18:56:12 +08005004 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005005 spv::Id extBuiltins = builder.import(name);
5006 extBuiltinMap[name] = extBuiltins;
5007 return extBuiltins;
5008 }
5009}
5010
John Kessenich140f3df2015-06-26 16:58:36 -06005011}; // end anonymous namespace
5012
5013namespace glslang {
5014
John Kessenich68d78fd2015-07-12 19:28:10 -06005015void GetSpirvVersion(std::string& version)
5016{
John Kessenich9e55f632015-07-15 10:03:39 -06005017 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005018 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005019 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005020 version = buf;
5021}
5022
John Kessenich140f3df2015-06-26 16:58:36 -06005023// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005024void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005025{
5026 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005027 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06005028 for (int i = 0; i < (int)spirv.size(); ++i) {
5029 unsigned int word = spirv[i];
5030 out.write((const char*)&word, 4);
5031 }
5032 out.close();
5033}
5034
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005035// Write SPIR-V out to a text file with 32-bit hexadecimal words
5036void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
5037{
5038 std::ofstream out;
5039 out.open(baseName, std::ios::binary | std::ios::out);
5040 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
5041 const int WORDS_PER_LINE = 8;
5042 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5043 out << "\t";
5044 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5045 const unsigned int word = spirv[i + j];
5046 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5047 if (i + j + 1 < (int)spirv.size()) {
5048 out << ",";
5049 }
5050 }
5051 out << std::endl;
5052 }
5053 out.close();
5054}
5055
John Kessenich140f3df2015-06-26 16:58:36 -06005056//
5057// Set up the glslang traversal
5058//
5059void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5060{
Lei Zhang17535f72016-05-04 15:55:59 -04005061 spv::SpvBuildLogger logger;
5062 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005063}
5064
Lei Zhang17535f72016-05-04 15:55:59 -04005065void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005066{
John Kessenich140f3df2015-06-26 16:58:36 -06005067 TIntermNode* root = intermediate.getTreeRoot();
5068
5069 if (root == 0)
5070 return;
5071
5072 glslang::GetThreadPoolAllocator().push();
5073
Lei Zhang17535f72016-05-04 15:55:59 -04005074 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005075
5076 root->traverse(&it);
5077
5078 it.dumpSpv(spirv);
5079
5080 glslang::GetThreadPoolAllocator().pop();
5081}
5082
5083}; // end namespace glslang