blob: 728658862e751ca9bfbc9f08db59322711622ab0 [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 {
45 #include "GLSL.std.450.h"
Rex Xu9d93a232016-05-05 12:30:44 +080046#ifdef AMD_EXTENSIONS
47 #include "GLSL.ext.AMD.h"
48#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060049}
John Kessenich140f3df2015-06-26 16:58:36 -060050
51// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020052#include "../glslang/MachineIndependent/localintermediate.h"
53#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060054#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050055#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060056
John Kessenich140f3df2015-06-26 16:58:36 -060057#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050058#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040059#include <list>
60#include <map>
61#include <stack>
62#include <string>
63#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060064
65namespace {
66
John Kessenich55e7d112015-11-15 21:33:39 -070067// For low-order part of the generator's magic number. Bump up
68// when there is a change in the style (e.g., if SSA form changes,
69// or a different instruction sequence to do something gets used).
70const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060071
qining4c912612016-04-01 10:35:16 -040072namespace {
73class SpecConstantOpModeGuard {
74public:
75 SpecConstantOpModeGuard(spv::Builder* builder)
76 : builder_(builder) {
77 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040078 }
79 ~SpecConstantOpModeGuard() {
80 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
81 : builder_->setToNormalCodeGenMode();
82 }
qining40887662016-04-03 22:20:42 -040083 void turnOnSpecConstantOpMode() {
84 builder_->setToSpecConstCodeGenMode();
85 }
qining4c912612016-04-01 10:35:16 -040086
87private:
88 spv::Builder* builder_;
89 bool previous_flag_;
90};
91}
92
John Kessenich140f3df2015-06-26 16:58:36 -060093//
94// The main holder of information for translating glslang to SPIR-V.
95//
96// Derives from the AST walking base class.
97//
98class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
99public:
Lei Zhang17535f72016-05-04 15:55:59 -0400100 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenich140f3df2015-06-26 16:58:36 -0600101 virtual ~TGlslangToSpvTraverser();
102
103 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
104 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
105 void visitConstantUnion(glslang::TIntermConstantUnion*);
106 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
107 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
108 void visitSymbol(glslang::TIntermSymbol* symbol);
109 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
110 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
111 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
112
John Kessenich7ba63412015-12-20 17:37:07 -0700113 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600114
115protected:
Rex Xubbceed72016-05-21 09:40:44 +0800116 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100117 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700118 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600119 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
120 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600121 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
122 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
123 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600124 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700125 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600126 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
127 glslang::TLayoutPacking, const glslang::TQualifier&);
128 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
129 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700130 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700131 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800132 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600133 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700134 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700135 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
136 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
137 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 +0100138 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600139
John Kessenich6fccb3c2016-09-19 16:01:41 -0600140 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600141 void makeFunctions(const glslang::TIntermSequence&);
142 void makeGlobalInitializers(const glslang::TIntermSequence&);
143 void visitFunctions(const glslang::TIntermSequence&);
144 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800145 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600146 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
147 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600148 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
149
qining25262b32016-05-06 17:25:16 -0400150 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);
151 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
152 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 +0800153 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 +0800154 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 -0600155 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800156 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800157 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy);
158#ifdef AMD_EXTENSIONS
159 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, spv::Id operand);
160#endif
John Kessenich5e4b1242015-08-06 22:53:06 -0600161 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 +0800162 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600163 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
164 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700165 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600166 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700167 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400168 spv::Id createSpvConstant(const glslang::TIntermTyped&);
169 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600170 bool isTrivialLeaf(const glslang::TIntermTyped* node);
171 bool isTrivial(const glslang::TIntermTyped* node);
172 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800173 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600174
175 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700176 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600177 int sequenceDepth;
178
Lei Zhang17535f72016-05-04 15:55:59 -0400179 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400180
John Kessenich140f3df2015-06-26 16:58:36 -0600181 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
182 spv::Builder builder;
183 bool inMain;
184 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700185 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 -0700186 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600187 const glslang::TIntermediate* glslangIntermediate;
188 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800189 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600190
John Kessenich2f273362015-07-18 22:34:27 -0600191 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600192 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600193 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700194 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600195 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 -0600196 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600197};
198
199//
200// Helper functions for translating glslang representations to SPIR-V enumerants.
201//
202
203// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700204spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600205{
John Kessenich66e2faf2016-03-12 18:34:36 -0700206 switch (source) {
207 case glslang::EShSourceGlsl:
208 switch (profile) {
209 case ENoProfile:
210 case ECoreProfile:
211 case ECompatibilityProfile:
212 return spv::SourceLanguageGLSL;
213 case EEsProfile:
214 return spv::SourceLanguageESSL;
215 default:
216 return spv::SourceLanguageUnknown;
217 }
218 case glslang::EShSourceHlsl:
Dan Baker55d5f2d2016-08-15 16:05:45 -0400219 //Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
220 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600221 default:
222 return spv::SourceLanguageUnknown;
223 }
224}
225
226// Translate glslang language (stage) to SPIR-V execution model.
227spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
228{
229 switch (stage) {
230 case EShLangVertex: return spv::ExecutionModelVertex;
231 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
232 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
233 case EShLangGeometry: return spv::ExecutionModelGeometry;
234 case EShLangFragment: return spv::ExecutionModelFragment;
235 case EShLangCompute: return spv::ExecutionModelGLCompute;
236 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700237 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600238 return spv::ExecutionModelFragment;
239 }
240}
241
242// Translate glslang type to SPIR-V storage class.
243spv::StorageClass TranslateStorageClass(const glslang::TType& type)
244{
245 if (type.getQualifier().isPipeInput())
246 return spv::StorageClassInput;
247 else if (type.getQualifier().isPipeOutput())
248 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700249 else if (type.getBasicType() == glslang::EbtSampler)
250 return spv::StorageClassUniformConstant;
251 else if (type.getBasicType() == glslang::EbtAtomicUint)
252 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600253 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700254 if (type.getQualifier().layoutPushConstant)
255 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600256 if (type.getBasicType() == glslang::EbtBlock)
257 return spv::StorageClassUniform;
258 else
259 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600260 // 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 -0600261 } else {
262 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700263 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
264 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
266 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400267 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700268 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600269 return spv::StorageClassFunction;
270 }
271 }
272}
273
274// Translate glslang sampler type to SPIR-V dimensionality.
275spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
276{
277 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700278 case glslang::Esd1D: return spv::Dim1D;
279 case glslang::Esd2D: return spv::Dim2D;
280 case glslang::Esd3D: return spv::Dim3D;
281 case glslang::EsdCube: return spv::DimCube;
282 case glslang::EsdRect: return spv::DimRect;
283 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700284 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600285 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700286 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600287 return spv::Dim2D;
288 }
289}
290
John Kessenichf6640762016-08-01 19:44:00 -0600291// Translate glslang precision to SPIR-V precision decorations.
292spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600293{
John Kessenichf6640762016-08-01 19:44:00 -0600294 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700295 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600296 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600297 default:
298 return spv::NoPrecision;
299 }
300}
301
John Kessenichf6640762016-08-01 19:44:00 -0600302// Translate glslang type to SPIR-V precision decorations.
303spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
304{
305 return TranslatePrecisionDecoration(type.getQualifier().precision);
306}
307
John Kessenich140f3df2015-06-26 16:58:36 -0600308// Translate glslang type to SPIR-V block decorations.
309spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
310{
311 if (type.getBasicType() == glslang::EbtBlock) {
312 switch (type.getQualifier().storage) {
313 case glslang::EvqUniform: return spv::DecorationBlock;
314 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
315 case glslang::EvqVaryingIn: return spv::DecorationBlock;
316 case glslang::EvqVaryingOut: return spv::DecorationBlock;
317 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700318 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600319 break;
320 }
321 }
322
John Kessenich4016e382016-07-15 11:53:56 -0600323 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600324}
325
Rex Xu1da878f2016-02-21 20:59:01 +0800326// Translate glslang type to SPIR-V memory decorations.
327void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
328{
329 if (qualifier.coherent)
330 memory.push_back(spv::DecorationCoherent);
331 if (qualifier.volatil)
332 memory.push_back(spv::DecorationVolatile);
333 if (qualifier.restrict)
334 memory.push_back(spv::DecorationRestrict);
335 if (qualifier.readonly)
336 memory.push_back(spv::DecorationNonWritable);
337 if (qualifier.writeonly)
338 memory.push_back(spv::DecorationNonReadable);
339}
340
John Kessenich140f3df2015-06-26 16:58:36 -0600341// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700342spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600343{
344 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700345 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600346 case glslang::ElmRowMajor:
347 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700348 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600349 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700350 default:
351 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600352 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600353 }
354 } else {
355 switch (type.getBasicType()) {
356 default:
John Kessenich4016e382016-07-15 11:53:56 -0600357 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600358 break;
359 case glslang::EbtBlock:
360 switch (type.getQualifier().storage) {
361 case glslang::EvqUniform:
362 case glslang::EvqBuffer:
363 switch (type.getQualifier().layoutPacking) {
364 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600365 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
366 default:
John Kessenich4016e382016-07-15 11:53:56 -0600367 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600368 }
369 case glslang::EvqVaryingIn:
370 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700371 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600372 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600373 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700374 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600375 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600376 }
377 }
378 }
379}
380
381// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600382// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700383// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800384spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600385{
Rex Xubbceed72016-05-21 09:40:44 +0800386 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700387 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600388 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800389 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700390 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700391 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600392 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800393#ifdef AMD_EXTENSIONS
394 else if (qualifier.explicitInterp)
395 return spv::DecorationExplicitInterpAMD;
396#endif
Rex Xubbceed72016-05-21 09:40:44 +0800397 else
John Kessenich4016e382016-07-15 11:53:56 -0600398 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800399}
400
401// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600402// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800403// should be applied.
404spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
405{
406 if (qualifier.patch)
407 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700408 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600409 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700410 else if (qualifier.sample) {
411 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600412 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700413 } else
John Kessenich4016e382016-07-15 11:53:56 -0600414 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600415}
416
John Kessenich92187592016-02-01 13:45:25 -0700417// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700418spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600419{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700420 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600421 return spv::DecorationInvariant;
422 else
John Kessenich4016e382016-07-15 11:53:56 -0600423 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600424}
425
qining9220dbb2016-05-04 17:34:38 -0400426// If glslang type is noContraction, return SPIR-V NoContraction decoration.
427spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
428{
429 if (qualifier.noContraction)
430 return spv::DecorationNoContraction;
431 else
John Kessenich4016e382016-07-15 11:53:56 -0600432 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400433}
434
David Netoa901ffe2016-06-08 14:11:40 +0100435// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
436// associated capabilities when required. For some built-in variables, a capability
437// is generated only when using the variable in an executable instruction, but not when
438// just declaring a struct member variable with it. This is true for PointSize,
439// ClipDistance, and CullDistance.
440spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600441{
442 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700443 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600444 // Defer adding the capability until the built-in is actually used.
445 if (! memberDeclaration) {
446 switch (glslangIntermediate->getStage()) {
447 case EShLangGeometry:
448 builder.addCapability(spv::CapabilityGeometryPointSize);
449 break;
450 case EShLangTessControl:
451 case EShLangTessEvaluation:
452 builder.addCapability(spv::CapabilityTessellationPointSize);
453 break;
454 default:
455 break;
456 }
John Kessenich92187592016-02-01 13:45:25 -0700457 }
458 return spv::BuiltInPointSize;
459
John Kessenichebb50532016-05-16 19:22:05 -0600460 // These *Distance capabilities logically belong here, but if the member is declared and
461 // then never used, consumers of SPIR-V prefer the capability not be declared.
462 // They are now generated when used, rather than here when declared.
463 // Potentially, the specification should be more clear what the minimum
464 // use needed is to trigger the capability.
465 //
John Kessenich92187592016-02-01 13:45:25 -0700466 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100467 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600468 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700469 return spv::BuiltInClipDistance;
470
471 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100472 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600473 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700474 return spv::BuiltInCullDistance;
475
476 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500477 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700478 return spv::BuiltInViewportIndex;
479
John Kessenich5e801132016-02-15 11:09:46 -0700480 case glslang::EbvSampleId:
481 builder.addCapability(spv::CapabilitySampleRateShading);
482 return spv::BuiltInSampleId;
483
484 case glslang::EbvSamplePosition:
485 builder.addCapability(spv::CapabilitySampleRateShading);
486 return spv::BuiltInSamplePosition;
487
488 case glslang::EbvSampleMask:
489 builder.addCapability(spv::CapabilitySampleRateShading);
490 return spv::BuiltInSampleMask;
491
John Kessenich78a45572016-07-08 14:05:15 -0600492 case glslang::EbvLayer:
493 builder.addCapability(spv::CapabilityGeometry);
494 return spv::BuiltInLayer;
495
John Kessenich140f3df2015-06-26 16:58:36 -0600496 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600497 case glslang::EbvVertexId: return spv::BuiltInVertexId;
498 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700499 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
500 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600501 case glslang::EbvBaseVertex:
502 case glslang::EbvBaseInstance:
503 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;
John Kessenich140f3df2015-06-26 16:58:36 -0600507 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
508 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600509 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
510 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
511 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
512 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
513 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
514 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
515 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600516 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
517 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
518 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
519 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
520 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
521 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
522 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
523 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800524 case glslang::EbvSubGroupSize:
525 case glslang::EbvSubGroupInvocation:
526 case glslang::EbvSubGroupEqMask:
527 case glslang::EbvSubGroupGeMask:
528 case glslang::EbvSubGroupGtMask:
529 case glslang::EbvSubGroupLeMask:
530 case glslang::EbvSubGroupLtMask:
531 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600532 logger->missingFunctionality("shader ballot");
John Kessenich4016e382016-07-15 11:53:56 -0600533 return spv::BuiltInMax;
Rex Xu9d93a232016-05-05 12:30:44 +0800534#ifdef AMD_EXTENSIONS
535 case glslang::EbvBaryCoordNoPersp: return spv::BuiltInBaryCoordNoPerspAMD;
536 case glslang::EbvBaryCoordNoPerspCentroid: return spv::BuiltInBaryCoordNoPerspCentroidAMD;
537 case glslang::EbvBaryCoordNoPerspSample: return spv::BuiltInBaryCoordNoPerspSampleAMD;
538 case glslang::EbvBaryCoordSmooth: return spv::BuiltInBaryCoordSmoothAMD;
539 case glslang::EbvBaryCoordSmoothCentroid: return spv::BuiltInBaryCoordSmoothCentroidAMD;
540 case glslang::EbvBaryCoordSmoothSample: return spv::BuiltInBaryCoordSmoothSampleAMD;
541 case glslang::EbvBaryCoordPullModel: return spv::BuiltInBaryCoordPullModelAMD;
542#endif
John Kessenich4016e382016-07-15 11:53:56 -0600543 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600544 }
545}
546
Rex Xufc618912015-09-09 16:42:49 +0800547// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700548spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800549{
550 assert(type.getBasicType() == glslang::EbtSampler);
551
John Kessenich5d0fa972016-02-15 11:57:00 -0700552 // Check for capabilities
553 switch (type.getQualifier().layoutFormat) {
554 case glslang::ElfRg32f:
555 case glslang::ElfRg16f:
556 case glslang::ElfR11fG11fB10f:
557 case glslang::ElfR16f:
558 case glslang::ElfRgba16:
559 case glslang::ElfRgb10A2:
560 case glslang::ElfRg16:
561 case glslang::ElfRg8:
562 case glslang::ElfR16:
563 case glslang::ElfR8:
564 case glslang::ElfRgba16Snorm:
565 case glslang::ElfRg16Snorm:
566 case glslang::ElfRg8Snorm:
567 case glslang::ElfR16Snorm:
568 case glslang::ElfR8Snorm:
569
570 case glslang::ElfRg32i:
571 case glslang::ElfRg16i:
572 case glslang::ElfRg8i:
573 case glslang::ElfR16i:
574 case glslang::ElfR8i:
575
576 case glslang::ElfRgb10a2ui:
577 case glslang::ElfRg32ui:
578 case glslang::ElfRg16ui:
579 case glslang::ElfRg8ui:
580 case glslang::ElfR16ui:
581 case glslang::ElfR8ui:
582 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
583 break;
584
585 default:
586 break;
587 }
588
589 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800590 switch (type.getQualifier().layoutFormat) {
591 case glslang::ElfNone: return spv::ImageFormatUnknown;
592 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
593 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
594 case glslang::ElfR32f: return spv::ImageFormatR32f;
595 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
596 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
597 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
598 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
599 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
600 case glslang::ElfR16f: return spv::ImageFormatR16f;
601 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
602 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
603 case glslang::ElfRg16: return spv::ImageFormatRg16;
604 case glslang::ElfRg8: return spv::ImageFormatRg8;
605 case glslang::ElfR16: return spv::ImageFormatR16;
606 case glslang::ElfR8: return spv::ImageFormatR8;
607 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
608 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
609 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
610 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
611 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
612 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
613 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
614 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
615 case glslang::ElfR32i: return spv::ImageFormatR32i;
616 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
617 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
618 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
619 case glslang::ElfR16i: return spv::ImageFormatR16i;
620 case glslang::ElfR8i: return spv::ImageFormatR8i;
621 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
622 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
623 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
624 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
625 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
626 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
627 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
628 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
629 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
630 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600631 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800632 }
633}
634
qining25262b32016-05-06 17:25:16 -0400635// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700636// descriptor set.
637bool IsDescriptorResource(const glslang::TType& type)
638{
John Kessenichf7497e22016-03-08 21:36:22 -0700639 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700640 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700641 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700642
643 // non block...
644 // basically samplerXXX/subpass/sampler/texture are all included
645 // if they are the global-scope-class, not the function parameter
646 // (or local, if they ever exist) class.
647 if (type.getBasicType() == glslang::EbtSampler)
648 return type.getQualifier().isUniformOrBuffer();
649
650 // None of the above.
651 return false;
652}
653
John Kesseniche0b6cad2015-12-24 10:30:13 -0700654void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
655{
656 if (child.layoutMatrix == glslang::ElmNone)
657 child.layoutMatrix = parent.layoutMatrix;
658
659 if (parent.invariant)
660 child.invariant = true;
661 if (parent.nopersp)
662 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800663#ifdef AMD_EXTENSIONS
664 if (parent.explicitInterp)
665 child.explicitInterp = true;
666#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700667 if (parent.flat)
668 child.flat = true;
669 if (parent.centroid)
670 child.centroid = true;
671 if (parent.patch)
672 child.patch = true;
673 if (parent.sample)
674 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800675 if (parent.coherent)
676 child.coherent = true;
677 if (parent.volatil)
678 child.volatil = true;
679 if (parent.restrict)
680 child.restrict = true;
681 if (parent.readonly)
682 child.readonly = true;
683 if (parent.writeonly)
684 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700685}
686
John Kessenichf2b7f332016-09-01 17:05:23 -0600687bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700688{
John Kessenich7b9fa252016-01-21 18:56:57 -0700689 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600690 // - struct members might inherit from a struct declaration
691 // (note that non-block structs don't explicitly inherit,
692 // only implicitly, meaning no decoration involved)
693 // - affect decorations on the struct members
694 // (note smooth does not, and expecting something like volatile
695 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700696 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600697 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700698}
699
John Kessenich140f3df2015-06-26 16:58:36 -0600700//
701// Implement the TGlslangToSpvTraverser class.
702//
703
Lei Zhang17535f72016-05-04 15:55:59 -0400704TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
705 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
706 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600707 inMain(false), mainTerminated(false), linkageOnly(false),
708 glslangIntermediate(glslangIntermediate)
709{
710 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
711
712 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700713 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600714 stdBuiltins = builder.import("GLSL.std.450");
715 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600716 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
717 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600718
719 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600720 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
721 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600722 builder.addSourceExtension(it->c_str());
723
724 // Add the top-level modes for this shader.
725
John Kessenich92187592016-02-01 13:45:25 -0700726 if (glslangIntermediate->getXfbMode()) {
727 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600728 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700729 }
John Kessenich140f3df2015-06-26 16:58:36 -0600730
731 unsigned int mode;
732 switch (glslangIntermediate->getStage()) {
733 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600734 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600735 break;
736
737 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600738 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600739 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
740 break;
741
742 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600743 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600744 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700745 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
746 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
747 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600748 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600749 }
John Kessenich4016e382016-07-15 11:53:56 -0600750 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600751 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
752
John Kesseniche6903322015-10-13 16:29:02 -0600753 switch (glslangIntermediate->getVertexSpacing()) {
754 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
755 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
756 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600757 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600758 }
John Kessenich4016e382016-07-15 11:53:56 -0600759 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600760 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
761
762 switch (glslangIntermediate->getVertexOrder()) {
763 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
764 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600765 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600766 }
John Kessenich4016e382016-07-15 11:53:56 -0600767 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600768 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
769
770 if (glslangIntermediate->getPointMode())
771 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600772 break;
773
774 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600775 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600776 switch (glslangIntermediate->getInputPrimitive()) {
777 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
778 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
779 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700780 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600781 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600782 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600783 }
John Kessenich4016e382016-07-15 11:53:56 -0600784 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600785 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600786
John Kessenich140f3df2015-06-26 16:58:36 -0600787 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
788
789 switch (glslangIntermediate->getOutputPrimitive()) {
790 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
791 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
792 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600793 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600794 }
John Kessenich4016e382016-07-15 11:53:56 -0600795 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600796 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
797 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
798 break;
799
800 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600801 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600802 if (glslangIntermediate->getPixelCenterInteger())
803 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600804
John Kessenich140f3df2015-06-26 16:58:36 -0600805 if (glslangIntermediate->getOriginUpperLeft())
806 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600807 else
808 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600809
810 if (glslangIntermediate->getEarlyFragmentTests())
811 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
812
813 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600814 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
815 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600816 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600817 }
John Kessenich4016e382016-07-15 11:53:56 -0600818 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600819 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
820
821 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
822 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600823 break;
824
825 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600826 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600827 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
828 glslangIntermediate->getLocalSize(1),
829 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600830 break;
831
832 default:
833 break;
834 }
835
836}
837
John Kessenich7ba63412015-12-20 17:37:07 -0700838// Finish everything and dump
839void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
840{
841 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100842 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
843 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700844
qiningda397332016-03-09 19:54:03 -0500845 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700846 builder.dump(out);
847}
848
John Kessenich140f3df2015-06-26 16:58:36 -0600849TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
850{
851 if (! mainTerminated) {
852 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
853 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600854 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600855 }
856}
857
858//
859// Implement the traversal functions.
860//
861// Return true from interior nodes to have the external traversal
862// continue on to children. Return false if children were
863// already processed.
864//
865
866//
qining25262b32016-05-06 17:25:16 -0400867// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600868// - uniform/input reads
869// - output writes
870// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
871// - something simple that degenerates into the last bullet
872//
873void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
874{
qining75d1d802016-04-06 14:42:01 -0400875 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
876 if (symbol->getType().getQualifier().isSpecConstant())
877 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
878
John Kessenich140f3df2015-06-26 16:58:36 -0600879 // getSymbolId() will set up all the IO decorations on the first call.
880 // Formal function parameters were mapped during makeFunctions().
881 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700882
883 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
884 if (builder.isPointer(id)) {
885 spv::StorageClass sc = builder.getStorageClass(id);
886 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
887 iOSet.insert(id);
888 }
889
890 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700891 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600892 // Prepare to generate code for the access
893
894 // L-value chains will be computed left to right. We're on the symbol now,
895 // which is the left-most part of the access chain, so now is "clear" time,
896 // followed by setting the base.
897 builder.clearAccessChain();
898
899 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700900 // except for
John Kessenich4bf71552016-09-02 11:20:21 -0600901 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -0700902 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -0600903 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -0700904 // These are also pure R-values.
905 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -0600906 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -0600907 builder.setAccessChainRValue(id);
908 else
909 builder.setAccessChainLValue(id);
910 }
911}
912
913bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
914{
qining40887662016-04-03 22:20:42 -0400915 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
916 if (node->getType().getQualifier().isSpecConstant())
917 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
918
John Kessenich140f3df2015-06-26 16:58:36 -0600919 // First, handle special cases
920 switch (node->getOp()) {
921 case glslang::EOpAssign:
922 case glslang::EOpAddAssign:
923 case glslang::EOpSubAssign:
924 case glslang::EOpMulAssign:
925 case glslang::EOpVectorTimesMatrixAssign:
926 case glslang::EOpVectorTimesScalarAssign:
927 case glslang::EOpMatrixTimesScalarAssign:
928 case glslang::EOpMatrixTimesMatrixAssign:
929 case glslang::EOpDivAssign:
930 case glslang::EOpModAssign:
931 case glslang::EOpAndAssign:
932 case glslang::EOpInclusiveOrAssign:
933 case glslang::EOpExclusiveOrAssign:
934 case glslang::EOpLeftShiftAssign:
935 case glslang::EOpRightShiftAssign:
936 // A bin-op assign "a += b" means the same thing as "a = a + b"
937 // where a is evaluated before b. For a simple assignment, GLSL
938 // says to evaluate the left before the right. So, always, left
939 // node then right node.
940 {
941 // get the left l-value, save it away
942 builder.clearAccessChain();
943 node->getLeft()->traverse(this);
944 spv::Builder::AccessChain lValue = builder.getAccessChain();
945
946 // evaluate the right
947 builder.clearAccessChain();
948 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700949 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600950
951 if (node->getOp() != glslang::EOpAssign) {
952 // the left is also an r-value
953 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700954 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600955
956 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -0600957 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -0400958 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600959 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
960 node->getType().getBasicType());
961
962 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700963 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600964 }
965
966 // store the result
967 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -0600968 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600969
970 // assignments are expressions having an rValue after they are evaluated...
971 builder.clearAccessChain();
972 builder.setAccessChainRValue(rValue);
973 }
974 return false;
975 case glslang::EOpIndexDirect:
976 case glslang::EOpIndexDirectStruct:
977 {
978 // Get the left part of the access chain.
979 node->getLeft()->traverse(this);
980
981 // Add the next element in the chain
982
David Netoa901ffe2016-06-08 14:11:40 +0100983 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600984 if (! node->getLeft()->getType().isArray() &&
985 node->getLeft()->getType().isVector() &&
986 node->getOp() == glslang::EOpIndexDirect) {
987 // This is essentially a hard-coded vector swizzle of size 1,
988 // so short circuit the access-chain stuff with a swizzle.
989 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +0100990 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -0600991 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600992 } else {
David Netoa901ffe2016-06-08 14:11:40 +0100993 int spvIndex = glslangIndex;
994 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
995 node->getOp() == glslang::EOpIndexDirectStruct)
996 {
997 // This may be, e.g., an anonymous block-member selection, which generally need
998 // index remapping due to hidden members in anonymous blocks.
999 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1000 assert(remapper.size() > 0);
1001 spvIndex = remapper[glslangIndex];
1002 }
John Kessenichebb50532016-05-16 19:22:05 -06001003
David Netoa901ffe2016-06-08 14:11:40 +01001004 // normal case for indexing array or structure or block
1005 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1006
1007 // Add capabilities here for accessing PointSize and clip/cull distance.
1008 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001009 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001010 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001011 }
1012 }
1013 return false;
1014 case glslang::EOpIndexIndirect:
1015 {
1016 // Structure or array or vector indirection.
1017 // Will use native SPIR-V access-chain for struct and array indirection;
1018 // matrices are arrays of vectors, so will also work for a matrix.
1019 // Will use the access chain's 'component' for variable index into a vector.
1020
1021 // This adapter is building access chains left to right.
1022 // Set up the access chain to the left.
1023 node->getLeft()->traverse(this);
1024
1025 // save it so that computing the right side doesn't trash it
1026 spv::Builder::AccessChain partial = builder.getAccessChain();
1027
1028 // compute the next index in the chain
1029 builder.clearAccessChain();
1030 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001031 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001032
1033 // restore the saved access chain
1034 builder.setAccessChain(partial);
1035
1036 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001037 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001038 else
John Kessenichfa668da2015-09-13 14:46:30 -06001039 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001040 }
1041 return false;
1042 case glslang::EOpVectorSwizzle:
1043 {
1044 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001045 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001046 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001047 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001048 }
1049 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001050 case glslang::EOpLogicalOr:
1051 case glslang::EOpLogicalAnd:
1052 {
1053
1054 // These may require short circuiting, but can sometimes be done as straight
1055 // binary operations. The right operand must be short circuited if it has
1056 // side effects, and should probably be if it is complex.
1057 if (isTrivial(node->getRight()->getAsTyped()))
1058 break; // handle below as a normal binary operation
1059 // otherwise, we need to do dynamic short circuiting on the right operand
1060 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1061 builder.clearAccessChain();
1062 builder.setAccessChainRValue(result);
1063 }
1064 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001065 default:
1066 break;
1067 }
1068
1069 // Assume generic binary op...
1070
John Kessenich32cfd492016-02-02 12:37:46 -07001071 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001072 builder.clearAccessChain();
1073 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001074 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001075
John Kessenich32cfd492016-02-02 12:37:46 -07001076 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001077 builder.clearAccessChain();
1078 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001079 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001080
John Kessenich32cfd492016-02-02 12:37:46 -07001081 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001082 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001083 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001084 convertGlslangToSpvType(node->getType()), left, right,
1085 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001086
John Kessenich50e57562015-12-21 21:21:11 -07001087 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001088 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001089 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001090 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001091 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001092 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001093 return false;
1094 }
John Kessenich140f3df2015-06-26 16:58:36 -06001095}
1096
1097bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1098{
qining40887662016-04-03 22:20:42 -04001099 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1100 if (node->getType().getQualifier().isSpecConstant())
1101 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1102
John Kessenichfc51d282015-08-19 13:34:18 -06001103 spv::Id result = spv::NoResult;
1104
1105 // try texturing first
1106 result = createImageTextureFunctionCall(node);
1107 if (result != spv::NoResult) {
1108 builder.clearAccessChain();
1109 builder.setAccessChainRValue(result);
1110
1111 return false; // done with this node
1112 }
1113
1114 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001115
1116 if (node->getOp() == glslang::EOpArrayLength) {
1117 // Quite special; won't want to evaluate the operand.
1118
1119 // Normal .length() would have been constant folded by the front-end.
1120 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001121 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001122 assert(node->getOperand()->getType().isRuntimeSizedArray());
1123 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1124 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001125 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1126 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001127
1128 builder.clearAccessChain();
1129 builder.setAccessChainRValue(length);
1130
1131 return false;
1132 }
1133
John Kessenichfc51d282015-08-19 13:34:18 -06001134 // Start by evaluating the operand
1135
John Kessenich8c8505c2016-07-26 12:50:38 -06001136 // Does it need a swizzle inversion? If so, evaluation is inverted;
1137 // operate first on the swizzle base, then apply the swizzle.
1138 spv::Id invertedType = spv::NoType;
1139 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1140 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1141 invertedType = getInvertedSwizzleType(*node->getOperand());
1142
John Kessenich140f3df2015-06-26 16:58:36 -06001143 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001144 if (invertedType != spv::NoType)
1145 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1146 else
1147 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001148
Rex Xufc618912015-09-09 16:42:49 +08001149 spv::Id operand = spv::NoResult;
1150
1151 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1152 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001153 node->getOp() == glslang::EOpAtomicCounter ||
1154 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001155 operand = builder.accessChainGetLValue(); // Special case l-value operands
1156 else
John Kessenich32cfd492016-02-02 12:37:46 -07001157 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001158
John Kessenichf6640762016-08-01 19:44:00 -06001159 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001160 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001161
1162 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001163 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001164 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001165
1166 // if not, then possibly an operation
1167 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001168 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001169
1170 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001171 if (invertedType)
1172 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1173
John Kessenich140f3df2015-06-26 16:58:36 -06001174 builder.clearAccessChain();
1175 builder.setAccessChainRValue(result);
1176
1177 return false; // done with this node
1178 }
1179
1180 // it must be a special case, check...
1181 switch (node->getOp()) {
1182 case glslang::EOpPostIncrement:
1183 case glslang::EOpPostDecrement:
1184 case glslang::EOpPreIncrement:
1185 case glslang::EOpPreDecrement:
1186 {
1187 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001188 spv::Id one = 0;
1189 if (node->getBasicType() == glslang::EbtFloat)
1190 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001191 else if (node->getBasicType() == glslang::EbtDouble)
1192 one = builder.makeDoubleConstant(1.0);
Rex Xu8ff43de2016-04-22 16:51:45 +08001193 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1194 one = builder.makeInt64Constant(1);
1195 else
1196 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001197 glslang::TOperator op;
1198 if (node->getOp() == glslang::EOpPreIncrement ||
1199 node->getOp() == glslang::EOpPostIncrement)
1200 op = glslang::EOpAdd;
1201 else
1202 op = glslang::EOpSub;
1203
John Kessenichf6640762016-08-01 19:44:00 -06001204 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001205 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001206 convertGlslangToSpvType(node->getType()), operand, one,
1207 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001208 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001209
1210 // The result of operation is always stored, but conditionally the
1211 // consumed result. The consumed result is always an r-value.
1212 builder.accessChainStore(result);
1213 builder.clearAccessChain();
1214 if (node->getOp() == glslang::EOpPreIncrement ||
1215 node->getOp() == glslang::EOpPreDecrement)
1216 builder.setAccessChainRValue(result);
1217 else
1218 builder.setAccessChainRValue(operand);
1219 }
1220
1221 return false;
1222
1223 case glslang::EOpEmitStreamVertex:
1224 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1225 return false;
1226 case glslang::EOpEndStreamPrimitive:
1227 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1228 return false;
1229
1230 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001231 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001232 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001233 }
John Kessenich140f3df2015-06-26 16:58:36 -06001234}
1235
1236bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1237{
qining27e04a02016-04-14 16:40:20 -04001238 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1239 if (node->getType().getQualifier().isSpecConstant())
1240 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1241
John Kessenichfc51d282015-08-19 13:34:18 -06001242 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001243 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1244 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001245
1246 // try texturing
1247 result = createImageTextureFunctionCall(node);
1248 if (result != spv::NoResult) {
1249 builder.clearAccessChain();
1250 builder.setAccessChainRValue(result);
1251
1252 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001253 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001254 // "imageStore" is a special case, which has no result
1255 return false;
1256 }
John Kessenichfc51d282015-08-19 13:34:18 -06001257
John Kessenich140f3df2015-06-26 16:58:36 -06001258 glslang::TOperator binOp = glslang::EOpNull;
1259 bool reduceComparison = true;
1260 bool isMatrix = false;
1261 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001262 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001263
1264 assert(node->getOp());
1265
John Kessenichf6640762016-08-01 19:44:00 -06001266 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001267
1268 switch (node->getOp()) {
1269 case glslang::EOpSequence:
1270 {
1271 if (preVisit)
1272 ++sequenceDepth;
1273 else
1274 --sequenceDepth;
1275
1276 if (sequenceDepth == 1) {
1277 // If this is the parent node of all the functions, we want to see them
1278 // early, so all call points have actual SPIR-V functions to reference.
1279 // In all cases, still let the traverser visit the children for us.
1280 makeFunctions(node->getAsAggregate()->getSequence());
1281
John Kessenich6fccb3c2016-09-19 16:01:41 -06001282 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001283 // anything else gets there, so visit out of order, doing them all now.
1284 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1285
1286 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1287 // so do them manually.
1288 visitFunctions(node->getAsAggregate()->getSequence());
1289
1290 return false;
1291 }
1292
1293 return true;
1294 }
1295 case glslang::EOpLinkerObjects:
1296 {
1297 if (visit == glslang::EvPreVisit)
1298 linkageOnly = true;
1299 else
1300 linkageOnly = false;
1301
1302 return true;
1303 }
1304 case glslang::EOpComma:
1305 {
1306 // processing from left to right naturally leaves the right-most
1307 // lying around in the access chain
1308 glslang::TIntermSequence& glslangOperands = node->getSequence();
1309 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1310 glslangOperands[i]->traverse(this);
1311
1312 return false;
1313 }
1314 case glslang::EOpFunction:
1315 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001316 if (isShaderEntryPoint(node)) {
John Kessenich140f3df2015-06-26 16:58:36 -06001317 inMain = true;
1318 builder.setBuildPoint(shaderEntry->getLastBlock());
1319 } else {
1320 handleFunctionEntry(node);
1321 }
1322 } else {
1323 if (inMain)
1324 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001325 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001326 inMain = false;
1327 }
1328
1329 return true;
1330 case glslang::EOpParameters:
1331 // Parameters will have been consumed by EOpFunction processing, but not
1332 // the body, so we still visited the function node's children, making this
1333 // child redundant.
1334 return false;
1335 case glslang::EOpFunctionCall:
1336 {
1337 if (node->isUserDefined())
1338 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001339 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1340 if (result) {
1341 builder.clearAccessChain();
1342 builder.setAccessChainRValue(result);
1343 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001344 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001345
1346 return false;
1347 }
1348 case glslang::EOpConstructMat2x2:
1349 case glslang::EOpConstructMat2x3:
1350 case glslang::EOpConstructMat2x4:
1351 case glslang::EOpConstructMat3x2:
1352 case glslang::EOpConstructMat3x3:
1353 case glslang::EOpConstructMat3x4:
1354 case glslang::EOpConstructMat4x2:
1355 case glslang::EOpConstructMat4x3:
1356 case glslang::EOpConstructMat4x4:
1357 case glslang::EOpConstructDMat2x2:
1358 case glslang::EOpConstructDMat2x3:
1359 case glslang::EOpConstructDMat2x4:
1360 case glslang::EOpConstructDMat3x2:
1361 case glslang::EOpConstructDMat3x3:
1362 case glslang::EOpConstructDMat3x4:
1363 case glslang::EOpConstructDMat4x2:
1364 case glslang::EOpConstructDMat4x3:
1365 case glslang::EOpConstructDMat4x4:
1366 isMatrix = true;
1367 // fall through
1368 case glslang::EOpConstructFloat:
1369 case glslang::EOpConstructVec2:
1370 case glslang::EOpConstructVec3:
1371 case glslang::EOpConstructVec4:
1372 case glslang::EOpConstructDouble:
1373 case glslang::EOpConstructDVec2:
1374 case glslang::EOpConstructDVec3:
1375 case glslang::EOpConstructDVec4:
1376 case glslang::EOpConstructBool:
1377 case glslang::EOpConstructBVec2:
1378 case glslang::EOpConstructBVec3:
1379 case glslang::EOpConstructBVec4:
1380 case glslang::EOpConstructInt:
1381 case glslang::EOpConstructIVec2:
1382 case glslang::EOpConstructIVec3:
1383 case glslang::EOpConstructIVec4:
1384 case glslang::EOpConstructUint:
1385 case glslang::EOpConstructUVec2:
1386 case glslang::EOpConstructUVec3:
1387 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001388 case glslang::EOpConstructInt64:
1389 case glslang::EOpConstructI64Vec2:
1390 case glslang::EOpConstructI64Vec3:
1391 case glslang::EOpConstructI64Vec4:
1392 case glslang::EOpConstructUint64:
1393 case glslang::EOpConstructU64Vec2:
1394 case glslang::EOpConstructU64Vec3:
1395 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001396 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001397 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001398 {
1399 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001400 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001401 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001402 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001403 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001404 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001405 std::vector<spv::Id> constituents;
1406 for (int c = 0; c < (int)arguments.size(); ++c)
1407 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001408 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001409 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001410 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001411 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001412 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001413
1414 builder.clearAccessChain();
1415 builder.setAccessChainRValue(constructed);
1416
1417 return false;
1418 }
1419
1420 // These six are component-wise compares with component-wise results.
1421 // Forward on to createBinaryOperation(), requesting a vector result.
1422 case glslang::EOpLessThan:
1423 case glslang::EOpGreaterThan:
1424 case glslang::EOpLessThanEqual:
1425 case glslang::EOpGreaterThanEqual:
1426 case glslang::EOpVectorEqual:
1427 case glslang::EOpVectorNotEqual:
1428 {
1429 // Map the operation to a binary
1430 binOp = node->getOp();
1431 reduceComparison = false;
1432 switch (node->getOp()) {
1433 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1434 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1435 default: binOp = node->getOp(); break;
1436 }
1437
1438 break;
1439 }
1440 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001441 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001442 binOp = glslang::EOpMul;
1443 break;
1444 case glslang::EOpOuterProduct:
1445 // two vectors multiplied to make a matrix
1446 binOp = glslang::EOpOuterProduct;
1447 break;
1448 case glslang::EOpDot:
1449 {
qining25262b32016-05-06 17:25:16 -04001450 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001451 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001452 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001453 binOp = glslang::EOpMul;
1454 break;
1455 }
1456 case glslang::EOpMod:
1457 // when an aggregate, this is the floating-point mod built-in function,
1458 // which can be emitted by the one in createBinaryOperation()
1459 binOp = glslang::EOpMod;
1460 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001461 case glslang::EOpEmitVertex:
1462 case glslang::EOpEndPrimitive:
1463 case glslang::EOpBarrier:
1464 case glslang::EOpMemoryBarrier:
1465 case glslang::EOpMemoryBarrierAtomicCounter:
1466 case glslang::EOpMemoryBarrierBuffer:
1467 case glslang::EOpMemoryBarrierImage:
1468 case glslang::EOpMemoryBarrierShared:
1469 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001470 case glslang::EOpAllMemoryBarrierWithGroupSync:
1471 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1472 case glslang::EOpWorkgroupMemoryBarrier:
1473 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001474 noReturnValue = true;
1475 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1476 break;
1477
John Kessenich426394d2015-07-23 10:22:48 -06001478 case glslang::EOpAtomicAdd:
1479 case glslang::EOpAtomicMin:
1480 case glslang::EOpAtomicMax:
1481 case glslang::EOpAtomicAnd:
1482 case glslang::EOpAtomicOr:
1483 case glslang::EOpAtomicXor:
1484 case glslang::EOpAtomicExchange:
1485 case glslang::EOpAtomicCompSwap:
1486 atomic = true;
1487 break;
1488
John Kessenich140f3df2015-06-26 16:58:36 -06001489 default:
1490 break;
1491 }
1492
1493 //
1494 // See if it maps to a regular operation.
1495 //
John Kessenich140f3df2015-06-26 16:58:36 -06001496 if (binOp != glslang::EOpNull) {
1497 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1498 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1499 assert(left && right);
1500
1501 builder.clearAccessChain();
1502 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001503 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001504
1505 builder.clearAccessChain();
1506 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001507 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001508
qining25262b32016-05-06 17:25:16 -04001509 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001510 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001511 left->getType().getBasicType(), reduceComparison);
1512
1513 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001514 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001515 builder.clearAccessChain();
1516 builder.setAccessChainRValue(result);
1517
1518 return false;
1519 }
1520
John Kessenich426394d2015-07-23 10:22:48 -06001521 //
1522 // Create the list of operands.
1523 //
John Kessenich140f3df2015-06-26 16:58:36 -06001524 glslang::TIntermSequence& glslangOperands = node->getSequence();
1525 std::vector<spv::Id> operands;
1526 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001527 // special case l-value operands; there are just a few
1528 bool lvalue = false;
1529 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001530 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001531 case glslang::EOpModf:
1532 if (arg == 1)
1533 lvalue = true;
1534 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001535 case glslang::EOpInterpolateAtSample:
1536 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001537#ifdef AMD_EXTENSIONS
1538 case glslang::EOpInterpolateAtVertex:
1539#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001540 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001541 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001542
1543 // Does it need a swizzle inversion? If so, evaluation is inverted;
1544 // operate first on the swizzle base, then apply the swizzle.
1545 if (glslangOperands[0]->getAsOperator() &&
1546 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1547 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1548 }
Rex Xu7a26c172015-12-08 17:12:09 +08001549 break;
Rex Xud4782c12015-09-06 16:30:11 +08001550 case glslang::EOpAtomicAdd:
1551 case glslang::EOpAtomicMin:
1552 case glslang::EOpAtomicMax:
1553 case glslang::EOpAtomicAnd:
1554 case glslang::EOpAtomicOr:
1555 case glslang::EOpAtomicXor:
1556 case glslang::EOpAtomicExchange:
1557 case glslang::EOpAtomicCompSwap:
1558 if (arg == 0)
1559 lvalue = true;
1560 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001561 case glslang::EOpAddCarry:
1562 case glslang::EOpSubBorrow:
1563 if (arg == 2)
1564 lvalue = true;
1565 break;
1566 case glslang::EOpUMulExtended:
1567 case glslang::EOpIMulExtended:
1568 if (arg >= 2)
1569 lvalue = true;
1570 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001571 default:
1572 break;
1573 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001574 builder.clearAccessChain();
1575 if (invertedType != spv::NoType && arg == 0)
1576 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1577 else
1578 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001579 if (lvalue)
1580 operands.push_back(builder.accessChainGetLValue());
1581 else
John Kessenich32cfd492016-02-02 12:37:46 -07001582 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001583 }
John Kessenich426394d2015-07-23 10:22:48 -06001584
1585 if (atomic) {
1586 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001587 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001588 } else {
1589 // Pass through to generic operations.
1590 switch (glslangOperands.size()) {
1591 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001592 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001593 break;
1594 case 1:
qining25262b32016-05-06 17:25:16 -04001595 result = createUnaryOperation(
1596 node->getOp(), precision,
1597 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001598 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001599 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001600 break;
1601 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001602 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001603 break;
1604 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001605 if (invertedType)
1606 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001607 }
1608
1609 if (noReturnValue)
1610 return false;
1611
1612 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001613 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001614 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001615 } else {
1616 builder.clearAccessChain();
1617 builder.setAccessChainRValue(result);
1618 return false;
1619 }
1620}
1621
1622bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1623{
1624 // This path handles both if-then-else and ?:
1625 // The if-then-else has a node type of void, while
1626 // ?: has a non-void node type
1627 spv::Id result = 0;
1628 if (node->getBasicType() != glslang::EbtVoid) {
1629 // don't handle this as just on-the-fly temporaries, because there will be two names
1630 // and better to leave SSA to later passes
1631 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1632 }
1633
1634 // emit the condition before doing anything with selection
1635 node->getCondition()->traverse(this);
1636
1637 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001638 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001639
1640 if (node->getTrueBlock()) {
1641 // emit the "then" statement
1642 node->getTrueBlock()->traverse(this);
1643 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001644 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001645 }
1646
1647 if (node->getFalseBlock()) {
1648 ifBuilder.makeBeginElse();
1649 // emit the "else" statement
1650 node->getFalseBlock()->traverse(this);
1651 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001652 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001653 }
1654
1655 ifBuilder.makeEndIf();
1656
1657 if (result) {
1658 // GLSL only has r-values as the result of a :?, but
1659 // if we have an l-value, that can be more efficient if it will
1660 // become the base of a complex r-value expression, because the
1661 // next layer copies r-values into memory to use the access-chain mechanism
1662 builder.clearAccessChain();
1663 builder.setAccessChainLValue(result);
1664 }
1665
1666 return false;
1667}
1668
1669bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1670{
1671 // emit and get the condition before doing anything with switch
1672 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001673 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001674
1675 // browse the children to sort out code segments
1676 int defaultSegment = -1;
1677 std::vector<TIntermNode*> codeSegments;
1678 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1679 std::vector<int> caseValues;
1680 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1681 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1682 TIntermNode* child = *c;
1683 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001684 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001685 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001686 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001687 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1688 } else
1689 codeSegments.push_back(child);
1690 }
1691
qining25262b32016-05-06 17:25:16 -04001692 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001693 // statements between the last case and the end of the switch statement
1694 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1695 (int)codeSegments.size() == defaultSegment)
1696 codeSegments.push_back(nullptr);
1697
1698 // make the switch statement
1699 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001700 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001701
1702 // emit all the code in the segments
1703 breakForLoop.push(false);
1704 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1705 builder.nextSwitchSegment(segmentBlocks, s);
1706 if (codeSegments[s])
1707 codeSegments[s]->traverse(this);
1708 else
1709 builder.addSwitchBreak();
1710 }
1711 breakForLoop.pop();
1712
1713 builder.endSwitch(segmentBlocks);
1714
1715 return false;
1716}
1717
1718void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1719{
1720 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001721 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001722
1723 builder.clearAccessChain();
1724 builder.setAccessChainRValue(constant);
1725}
1726
1727bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1728{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001729 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001730 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001731 // Spec requires back edges to target header blocks, and every header block
1732 // must dominate its merge block. Make a header block first to ensure these
1733 // conditions are met. By definition, it will contain OpLoopMerge, followed
1734 // by a block-ending branch. But we don't want to put any other body/test
1735 // instructions in it, since the body/test may have arbitrary instructions,
1736 // including merges of its own.
1737 builder.setBuildPoint(&blocks.head);
1738 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001739 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001740 spv::Block& test = builder.makeNewBlock();
1741 builder.createBranch(&test);
1742
1743 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001744 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001745 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001746 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001747 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1748
1749 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001750 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001751 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001752 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001753 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001754 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001755
1756 builder.setBuildPoint(&blocks.continue_target);
1757 if (node->getTerminal())
1758 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001759 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001760 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001761 builder.createBranch(&blocks.body);
1762
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001763 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001764 builder.setBuildPoint(&blocks.body);
1765 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001766 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001767 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001768 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001769
1770 builder.setBuildPoint(&blocks.continue_target);
1771 if (node->getTerminal())
1772 node->getTerminal()->traverse(this);
1773 if (node->getTest()) {
1774 node->getTest()->traverse(this);
1775 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001776 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001777 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001778 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001779 // TODO: unless there was a break/return/discard instruction
1780 // somewhere in the body, this is an infinite loop, so we should
1781 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001782 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001783 }
John Kessenich140f3df2015-06-26 16:58:36 -06001784 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001785 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001786 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001787 return false;
1788}
1789
1790bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1791{
1792 if (node->getExpression())
1793 node->getExpression()->traverse(this);
1794
1795 switch (node->getFlowOp()) {
1796 case glslang::EOpKill:
1797 builder.makeDiscard();
1798 break;
1799 case glslang::EOpBreak:
1800 if (breakForLoop.top())
1801 builder.createLoopExit();
1802 else
1803 builder.addSwitchBreak();
1804 break;
1805 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001806 builder.createLoopContinue();
1807 break;
1808 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001809 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001810 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001811 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001812 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001813
1814 builder.clearAccessChain();
1815 break;
1816
1817 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001818 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001819 break;
1820 }
1821
1822 return false;
1823}
1824
1825spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1826{
qining25262b32016-05-06 17:25:16 -04001827 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001828 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001829 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001830 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001831 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001832 }
1833
1834 // Now, handle actual variables
1835 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1836 spv::Id spvType = convertGlslangToSpvType(node->getType());
1837
1838 const char* name = node->getName().c_str();
1839 if (glslang::IsAnonymous(name))
1840 name = "";
1841
1842 return builder.createVariable(storageClass, spvType, name);
1843}
1844
1845// Return type Id of the sampled type.
1846spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1847{
1848 switch (sampler.type) {
1849 case glslang::EbtFloat: return builder.makeFloatType(32);
1850 case glslang::EbtInt: return builder.makeIntType(32);
1851 case glslang::EbtUint: return builder.makeUintType(32);
1852 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001853 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001854 return builder.makeFloatType(32);
1855 }
1856}
1857
John Kessenich8c8505c2016-07-26 12:50:38 -06001858// If node is a swizzle operation, return the type that should be used if
1859// the swizzle base is first consumed by another operation, before the swizzle
1860// is applied.
1861spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1862{
1863 if (node.getAsOperator() &&
1864 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1865 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1866 else
1867 return spv::NoType;
1868}
1869
1870// When inverting a swizzle with a parent op, this function
1871// will apply the swizzle operation to a completed parent operation.
1872spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1873{
1874 std::vector<unsigned> swizzle;
1875 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1876 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1877}
1878
1879
1880// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1881void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1882{
1883 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1884 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1885 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1886}
1887
John Kessenich3ac051e2015-12-20 11:29:16 -07001888// Convert from a glslang type to an SPV type, by calling into a
1889// recursive version of this function. This establishes the inherited
1890// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001891spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1892{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001893 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001894}
1895
1896// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001897// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001898// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001899spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001900{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001901 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001902
1903 switch (type.getBasicType()) {
1904 case glslang::EbtVoid:
1905 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001906 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001907 break;
1908 case glslang::EbtFloat:
1909 spvType = builder.makeFloatType(32);
1910 break;
1911 case glslang::EbtDouble:
1912 spvType = builder.makeFloatType(64);
1913 break;
1914 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001915 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1916 // a 32-bit int where non-0 means true.
1917 if (explicitLayout != glslang::ElpNone)
1918 spvType = builder.makeUintType(32);
1919 else
1920 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001921 break;
1922 case glslang::EbtInt:
1923 spvType = builder.makeIntType(32);
1924 break;
1925 case glslang::EbtUint:
1926 spvType = builder.makeUintType(32);
1927 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001928 case glslang::EbtInt64:
1929 builder.addCapability(spv::CapabilityInt64);
1930 spvType = builder.makeIntType(64);
1931 break;
1932 case glslang::EbtUint64:
1933 builder.addCapability(spv::CapabilityInt64);
1934 spvType = builder.makeUintType(64);
1935 break;
John Kessenich426394d2015-07-23 10:22:48 -06001936 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06001937 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06001938 spvType = builder.makeUintType(32);
1939 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001940 case glslang::EbtSampler:
1941 {
1942 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001943 if (sampler.sampler) {
1944 // pure sampler
1945 spvType = builder.makeSamplerType();
1946 } else {
1947 // an image is present, make its type
1948 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1949 sampler.image ? 2 : 1, TranslateImageFormat(type));
1950 if (sampler.combined) {
1951 // already has both image and sampler, make the combined type
1952 spvType = builder.makeSampledImageType(spvType);
1953 }
John Kessenich55e7d112015-11-15 21:33:39 -07001954 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001955 }
John Kessenich140f3df2015-06-26 16:58:36 -06001956 break;
1957 case glslang::EbtStruct:
1958 case glslang::EbtBlock:
1959 {
1960 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06001961 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001962
1963 // Try to share structs for different layouts, but not yet for other
1964 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06001965 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06001966 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07001967 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001968 break;
1969
1970 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06001971 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06001972 memberRemapper[glslangMembers].resize(glslangMembers->size());
1973 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06001974 }
1975 break;
1976 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001977 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001978 break;
1979 }
1980
1981 if (type.isMatrix())
1982 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1983 else {
1984 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1985 if (type.getVectorSize() > 1)
1986 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1987 }
1988
1989 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001990 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1991
John Kessenichc9a80832015-09-12 12:17:44 -06001992 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001993 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001994 // We need to decorate array strides for types needing explicit layout, except blocks.
1995 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001996 // Use a dummy glslang type for querying internal strides of
1997 // arrays of arrays, but using just a one-dimensional array.
1998 glslang::TType simpleArrayType(type, 0); // deference type of the array
1999 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2000 simpleArrayType.getArraySizes().dereference();
2001
2002 // Will compute the higher-order strides here, rather than making a whole
2003 // pile of types and doing repetitive recursion on their contents.
2004 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2005 }
John Kessenichf8842e52016-01-04 19:22:56 -07002006
2007 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002008 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002009 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002010 if (stride > 0)
2011 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002012 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002013 }
2014 } else {
2015 // single-dimensional array, and don't yet have stride
2016
John Kessenichf8842e52016-01-04 19:22:56 -07002017 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002018 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2019 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002020 }
John Kessenich31ed4832015-09-09 17:51:38 -06002021
John Kessenichc9a80832015-09-12 12:17:44 -06002022 // Do the outer dimension, which might not be known for a runtime-sized array
2023 if (type.isRuntimeSizedArray()) {
2024 spvType = builder.makeRuntimeArray(spvType);
2025 } else {
2026 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002027 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002028 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002029 if (stride > 0)
2030 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002031 }
2032
2033 return spvType;
2034}
2035
John Kessenich6090df02016-06-30 21:18:02 -06002036
2037// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2038// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2039// Mutually recursive with convertGlslangToSpvType().
2040spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2041 const glslang::TTypeList* glslangMembers,
2042 glslang::TLayoutPacking explicitLayout,
2043 const glslang::TQualifier& qualifier)
2044{
2045 // Create a vector of struct types for SPIR-V to consume
2046 std::vector<spv::Id> spvMembers;
2047 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2048 int locationOffset = 0; // for use across struct members, when they are called recursively
2049 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2050 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2051 if (glslangMember.hiddenMember()) {
2052 ++memberDelta;
2053 if (type.getBasicType() == glslang::EbtBlock)
2054 memberRemapper[glslangMembers][i] = -1;
2055 } else {
2056 if (type.getBasicType() == glslang::EbtBlock)
2057 memberRemapper[glslangMembers][i] = i - memberDelta;
2058 // modify just this child's view of the qualifier
2059 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2060 InheritQualifiers(memberQualifier, qualifier);
2061
2062 // manually inherit location; it's more complex
2063 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2064 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2065 if (qualifier.hasLocation())
2066 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2067
2068 // recurse
2069 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2070 }
2071 }
2072
2073 // Make the SPIR-V type
2074 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002075 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002076 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2077
2078 // Decorate it
2079 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2080
2081 return spvType;
2082}
2083
2084void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2085 const glslang::TTypeList* glslangMembers,
2086 glslang::TLayoutPacking explicitLayout,
2087 const glslang::TQualifier& qualifier,
2088 spv::Id spvType)
2089{
2090 // Name and decorate the non-hidden members
2091 int offset = -1;
2092 int locationOffset = 0; // for use within the members of this struct
2093 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2094 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2095 int member = i;
2096 if (type.getBasicType() == glslang::EbtBlock)
2097 member = memberRemapper[glslangMembers][i];
2098
2099 // modify just this child's view of the qualifier
2100 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2101 InheritQualifiers(memberQualifier, qualifier);
2102
2103 // using -1 above to indicate a hidden member
2104 if (member >= 0) {
2105 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2106 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2107 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2108 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2109 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2110 if (type.getBasicType() == glslang::EbtBlock) {
2111 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2112 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2113 }
2114 }
2115 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2116
2117 if (qualifier.storage == glslang::EvqBuffer) {
2118 std::vector<spv::Decoration> memory;
2119 TranslateMemoryDecoration(memberQualifier, memory);
2120 for (unsigned int i = 0; i < memory.size(); ++i)
2121 addMemberDecoration(spvType, member, memory[i]);
2122 }
2123
John Kessenich2f47bc92016-06-30 21:47:35 -06002124 // Compute location decoration; tricky based on whether inheritance is at play and
2125 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002126 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2127 // probably move to the linker stage of the front end proper, and just have the
2128 // answer sitting already distributed throughout the individual member locations.
2129 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002130 // Ignore member locations if the container is an array, as that's
2131 // ill-specified and decisions have been made to not allow this anyway.
2132 // The object itself must have a location, and that comes out from decorating the object,
2133 // not the type (this code decorates types).
2134 if (! type.isArray()) {
2135 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2136 // struct members should not have explicit locations
2137 assert(type.getBasicType() != glslang::EbtStruct);
2138 location = memberQualifier.layoutLocation;
2139 } else if (type.getBasicType() != glslang::EbtBlock) {
2140 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2141 // The members, and their nested types, must not themselves have Location decorations.
2142 } else if (qualifier.hasLocation()) // inheritance
2143 location = qualifier.layoutLocation + locationOffset;
2144 }
John Kessenich6090df02016-06-30 21:18:02 -06002145 if (location >= 0)
2146 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2147
John Kessenich2f47bc92016-06-30 21:47:35 -06002148 if (qualifier.hasLocation()) // track for upcoming inheritance
2149 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2150
John Kessenich6090df02016-06-30 21:18:02 -06002151 // component, XFB, others
2152 if (glslangMember.getQualifier().hasComponent())
2153 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2154 if (glslangMember.getQualifier().hasXfbOffset())
2155 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2156 else if (explicitLayout != glslang::ElpNone) {
2157 // figure out what to do with offset, which is accumulating
2158 int nextOffset;
2159 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2160 if (offset >= 0)
2161 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2162 offset = nextOffset;
2163 }
2164
2165 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2166 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2167
2168 // built-in variable decorations
2169 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002170 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002171 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2172 }
2173 }
2174
2175 // Decorate the structure
2176 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2177 addDecoration(spvType, TranslateBlockDecoration(type));
2178 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2179 builder.addCapability(spv::CapabilityGeometryStreams);
2180 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2181 }
2182 if (glslangIntermediate->getXfbMode()) {
2183 builder.addCapability(spv::CapabilityTransformFeedback);
2184 if (type.getQualifier().hasXfbStride())
2185 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2186 if (type.getQualifier().hasXfbBuffer())
2187 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2188 }
2189}
2190
John Kessenich6c292d32016-02-15 20:58:50 -07002191// Turn the expression forming the array size into an id.
2192// This is not quite trivial, because of specialization constants.
2193// Sometimes, a raw constant is turned into an Id, and sometimes
2194// a specialization constant expression is.
2195spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2196{
2197 // First, see if this is sized with a node, meaning a specialization constant:
2198 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2199 if (specNode != nullptr) {
2200 builder.clearAccessChain();
2201 specNode->traverse(this);
2202 return accessChainLoad(specNode->getAsTyped()->getType());
2203 }
qining25262b32016-05-06 17:25:16 -04002204
John Kessenich6c292d32016-02-15 20:58:50 -07002205 // Otherwise, need a compile-time (front end) size, get it:
2206 int size = arraySizes.getDimSize(dim);
2207 assert(size > 0);
2208 return builder.makeUintConstant(size);
2209}
2210
John Kessenich103bef92016-02-08 21:38:15 -07002211// Wrap the builder's accessChainLoad to:
2212// - localize handling of RelaxedPrecision
2213// - use the SPIR-V inferred type instead of another conversion of the glslang type
2214// (avoids unnecessary work and possible type punning for structures)
2215// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002216spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2217{
John Kessenich103bef92016-02-08 21:38:15 -07002218 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2219 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2220
2221 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002222 if (type.getBasicType() == glslang::EbtBool) {
2223 if (builder.isScalarType(nominalTypeId)) {
2224 // Conversion for bool
2225 spv::Id boolType = builder.makeBoolType();
2226 if (nominalTypeId != boolType)
2227 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2228 } else if (builder.isVectorType(nominalTypeId)) {
2229 // Conversion for bvec
2230 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2231 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2232 if (nominalTypeId != bvecType)
2233 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2234 }
2235 }
John Kessenich103bef92016-02-08 21:38:15 -07002236
2237 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002238}
2239
Rex Xu27253232016-02-23 17:51:09 +08002240// Wrap the builder's accessChainStore to:
2241// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002242//
2243// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002244void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2245{
2246 // Need to convert to abstract types when necessary
2247 if (type.getBasicType() == glslang::EbtBool) {
2248 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2249
2250 if (builder.isScalarType(nominalTypeId)) {
2251 // Conversion for bool
2252 spv::Id boolType = builder.makeBoolType();
2253 if (nominalTypeId != boolType) {
2254 spv::Id zero = builder.makeUintConstant(0);
2255 spv::Id one = builder.makeUintConstant(1);
2256 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2257 }
2258 } else if (builder.isVectorType(nominalTypeId)) {
2259 // Conversion for bvec
2260 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2261 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2262 if (nominalTypeId != bvecType) {
2263 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2264 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2265 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2266 }
2267 }
2268 }
2269
2270 builder.accessChainStore(rvalue);
2271}
2272
John Kessenich4bf71552016-09-02 11:20:21 -06002273// For storing when types match at the glslang level, but not might match at the
2274// SPIR-V level.
2275//
2276// This especially happens when a single glslang type expands to multiple
2277// SPIR-V types, like a struct that is used in an member-undecorated way as well
2278// as in a member-decorated way.
2279//
2280// NOTE: This function can handle any store request; if it's not special it
2281// simplifies to a simple OpStore.
2282//
2283// Implicitly uses the existing builder.accessChain as the storage target.
2284void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2285{
John Kessenichb3e24e42016-09-11 12:33:43 -06002286 // we only do the complex path here if it's an aggregate
2287 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002288 accessChainStore(type, rValue);
2289 return;
2290 }
2291
John Kessenichb3e24e42016-09-11 12:33:43 -06002292 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002293 spv::Id rType = builder.getTypeId(rValue);
2294 spv::Id lValue = builder.accessChainGetLValue();
2295 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2296 if (lType == rType) {
2297 accessChainStore(type, rValue);
2298 return;
2299 }
2300
John Kessenichb3e24e42016-09-11 12:33:43 -06002301 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002302 // where the two types were the same type in GLSL. This requires member
2303 // by member copy, recursively.
2304
John Kessenichb3e24e42016-09-11 12:33:43 -06002305 // If an array, copy element by element.
2306 if (type.isArray()) {
2307 glslang::TType glslangElementType(type, 0);
2308 spv::Id elementRType = builder.getContainedTypeId(rType);
2309 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2310 // get the source member
2311 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002312
John Kessenichb3e24e42016-09-11 12:33:43 -06002313 // set up the target storage
2314 builder.clearAccessChain();
2315 builder.setAccessChainLValue(lValue);
2316 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002317
John Kessenichb3e24e42016-09-11 12:33:43 -06002318 // store the member
2319 multiTypeStore(glslangElementType, elementRValue);
2320 }
2321 } else {
2322 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002323
John Kessenichb3e24e42016-09-11 12:33:43 -06002324 // loop over structure members
2325 const glslang::TTypeList& members = *type.getStruct();
2326 for (int m = 0; m < (int)members.size(); ++m) {
2327 const glslang::TType& glslangMemberType = *members[m].type;
2328
2329 // get the source member
2330 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2331 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2332
2333 // set up the target storage
2334 builder.clearAccessChain();
2335 builder.setAccessChainLValue(lValue);
2336 builder.accessChainPush(builder.makeIntConstant(m));
2337
2338 // store the member
2339 multiTypeStore(glslangMemberType, memberRValue);
2340 }
John Kessenich4bf71552016-09-02 11:20:21 -06002341 }
2342}
2343
John Kessenichf85e8062015-12-19 13:57:10 -07002344// Decide whether or not this type should be
2345// decorated with offsets and strides, and if so
2346// whether std140 or std430 rules should be applied.
2347glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002348{
John Kessenichf85e8062015-12-19 13:57:10 -07002349 // has to be a block
2350 if (type.getBasicType() != glslang::EbtBlock)
2351 return glslang::ElpNone;
2352
2353 // has to be a uniform or buffer block
2354 if (type.getQualifier().storage != glslang::EvqUniform &&
2355 type.getQualifier().storage != glslang::EvqBuffer)
2356 return glslang::ElpNone;
2357
2358 // return the layout to use
2359 switch (type.getQualifier().layoutPacking) {
2360 case glslang::ElpStd140:
2361 case glslang::ElpStd430:
2362 return type.getQualifier().layoutPacking;
2363 default:
2364 return glslang::ElpNone;
2365 }
John Kessenich31ed4832015-09-09 17:51:38 -06002366}
2367
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002368// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002369int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002370{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002371 int size;
John Kessenich49987892015-12-29 17:11:44 -07002372 int stride;
2373 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002374
2375 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002376}
2377
John Kessenich49987892015-12-29 17:11:44 -07002378// 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 -07002379// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002380int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002381{
John Kessenich49987892015-12-29 17:11:44 -07002382 glslang::TType elementType;
2383 elementType.shallowCopy(matrixType);
2384 elementType.clearArraySizes();
2385
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002386 int size;
John Kessenich49987892015-12-29 17:11:44 -07002387 int stride;
2388 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2389
2390 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002391}
2392
John Kessenich5e4b1242015-08-06 22:53:06 -06002393// Given a member type of a struct, realign the current offset for it, and compute
2394// the next (not yet aligned) offset for the next member, which will get aligned
2395// on the next call.
2396// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2397// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2398// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002399void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002400 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002401{
2402 // this will get a positive value when deemed necessary
2403 nextOffset = -1;
2404
John Kessenich5e4b1242015-08-06 22:53:06 -06002405 // override anything in currentOffset with user-set offset
2406 if (memberType.getQualifier().hasOffset())
2407 currentOffset = memberType.getQualifier().layoutOffset;
2408
2409 // It could be that current linker usage in glslang updated all the layoutOffset,
2410 // in which case the following code does not matter. But, that's not quite right
2411 // once cross-compilation unit GLSL validation is done, as the original user
2412 // settings are needed in layoutOffset, and then the following will come into play.
2413
John Kessenichf85e8062015-12-19 13:57:10 -07002414 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002415 if (! memberType.getQualifier().hasOffset())
2416 currentOffset = -1;
2417
2418 return;
2419 }
2420
John Kessenichf85e8062015-12-19 13:57:10 -07002421 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002422 if (currentOffset < 0)
2423 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002424
John Kessenich5e4b1242015-08-06 22:53:06 -06002425 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2426 // but possibly not yet correctly aligned.
2427
2428 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002429 int dummyStride;
2430 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002431 glslang::RoundToPow2(currentOffset, memberAlignment);
2432 nextOffset = currentOffset + memberSize;
2433}
2434
David Netoa901ffe2016-06-08 14:11:40 +01002435void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002436{
David Netoa901ffe2016-06-08 14:11:40 +01002437 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2438 switch (glslangBuiltIn)
2439 {
2440 case glslang::EbvClipDistance:
2441 case glslang::EbvCullDistance:
2442 case glslang::EbvPointSize:
2443 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2444 // Alternately, we could just call this for any glslang built-in, since the
2445 // capability already guards against duplicates.
2446 TranslateBuiltInDecoration(glslangBuiltIn, false);
2447 break;
2448 default:
2449 // Capabilities were already generated when the struct was declared.
2450 break;
2451 }
John Kessenichebb50532016-05-16 19:22:05 -06002452}
2453
John Kessenich6fccb3c2016-09-19 16:01:41 -06002454bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002455{
John Kessenicheee9d532016-09-19 18:09:30 -06002456 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002457}
2458
2459// Make all the functions, skeletally, without actually visiting their bodies.
2460void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2461{
2462 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2463 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002464 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002465 continue;
2466
2467 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002468 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002469 //
qining25262b32016-05-06 17:25:16 -04002470 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002471 // function. What it is an address of varies:
2472 //
John Kessenich4bf71552016-09-02 11:20:21 -06002473 // - "in" parameters not marked as "const" can be written to without modifying the calling
2474 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002475 //
2476 // - "const in" parameters can just be the r-value, as no writes need occur.
2477 //
John Kessenich4bf71552016-09-02 11:20:21 -06002478 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2479 // 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 -06002480
2481 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002482 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002483 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2484
2485 for (int p = 0; p < (int)parameters.size(); ++p) {
2486 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2487 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002488 if (paramType.isOpaque())
2489 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2490 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002491 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2492 else
John Kessenich4bf71552016-09-02 11:20:21 -06002493 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002494 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002495 paramTypes.push_back(typeId);
2496 }
2497
2498 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002499 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2500 convertGlslangToSpvType(glslFunction->getType()),
2501 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002502
2503 // Track function to emit/call later
2504 functionMap[glslFunction->getName().c_str()] = function;
2505
2506 // Set the parameter id's
2507 for (int p = 0; p < (int)parameters.size(); ++p) {
2508 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2509 // give a name too
2510 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2511 }
2512 }
2513}
2514
2515// Process all the initializers, while skipping the functions and link objects
2516void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2517{
2518 builder.setBuildPoint(shaderEntry->getLastBlock());
2519 for (int i = 0; i < (int)initializers.size(); ++i) {
2520 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2521 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2522
2523 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002524 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002525 initializer->traverse(this);
2526 }
2527 }
2528}
2529
2530// Process all the functions, while skipping initializers.
2531void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2532{
2533 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2534 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2535 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2536 node->traverse(this);
2537 }
2538}
2539
2540void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2541{
qining25262b32016-05-06 17:25:16 -04002542 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002543 // that called makeFunctions().
2544 spv::Function* function = functionMap[node->getName().c_str()];
2545 spv::Block* functionBlock = function->getEntryBlock();
2546 builder.setBuildPoint(functionBlock);
2547}
2548
Rex Xu04db3f52015-09-16 11:44:02 +08002549void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002550{
Rex Xufc618912015-09-09 16:42:49 +08002551 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002552
2553 glslang::TSampler sampler = {};
2554 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002555 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002556 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2557 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2558 }
2559
John Kessenich140f3df2015-06-26 16:58:36 -06002560 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2561 builder.clearAccessChain();
2562 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002563
2564 // Special case l-value operands
2565 bool lvalue = false;
2566 switch (node.getOp()) {
2567 case glslang::EOpImageAtomicAdd:
2568 case glslang::EOpImageAtomicMin:
2569 case glslang::EOpImageAtomicMax:
2570 case glslang::EOpImageAtomicAnd:
2571 case glslang::EOpImageAtomicOr:
2572 case glslang::EOpImageAtomicXor:
2573 case glslang::EOpImageAtomicExchange:
2574 case glslang::EOpImageAtomicCompSwap:
2575 if (i == 0)
2576 lvalue = true;
2577 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002578 case glslang::EOpSparseImageLoad:
2579 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2580 lvalue = true;
2581 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002582 case glslang::EOpSparseTexture:
2583 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2584 lvalue = true;
2585 break;
2586 case glslang::EOpSparseTextureClamp:
2587 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2588 lvalue = true;
2589 break;
2590 case glslang::EOpSparseTextureLod:
2591 case glslang::EOpSparseTextureOffset:
2592 if (i == 3)
2593 lvalue = true;
2594 break;
2595 case glslang::EOpSparseTextureFetch:
2596 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2597 lvalue = true;
2598 break;
2599 case glslang::EOpSparseTextureFetchOffset:
2600 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2601 lvalue = true;
2602 break;
2603 case glslang::EOpSparseTextureLodOffset:
2604 case glslang::EOpSparseTextureGrad:
2605 case glslang::EOpSparseTextureOffsetClamp:
2606 if (i == 4)
2607 lvalue = true;
2608 break;
2609 case glslang::EOpSparseTextureGradOffset:
2610 case glslang::EOpSparseTextureGradClamp:
2611 if (i == 5)
2612 lvalue = true;
2613 break;
2614 case glslang::EOpSparseTextureGradOffsetClamp:
2615 if (i == 6)
2616 lvalue = true;
2617 break;
2618 case glslang::EOpSparseTextureGather:
2619 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2620 lvalue = true;
2621 break;
2622 case glslang::EOpSparseTextureGatherOffset:
2623 case glslang::EOpSparseTextureGatherOffsets:
2624 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2625 lvalue = true;
2626 break;
Rex Xufc618912015-09-09 16:42:49 +08002627 default:
2628 break;
2629 }
2630
Rex Xu6b86d492015-09-16 17:48:22 +08002631 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002632 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002633 else
John Kessenich32cfd492016-02-02 12:37:46 -07002634 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002635 }
2636}
2637
John Kessenichfc51d282015-08-19 13:34:18 -06002638void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002639{
John Kessenichfc51d282015-08-19 13:34:18 -06002640 builder.clearAccessChain();
2641 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002642 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002643}
John Kessenich140f3df2015-06-26 16:58:36 -06002644
John Kessenichfc51d282015-08-19 13:34:18 -06002645spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2646{
Rex Xufc618912015-09-09 16:42:49 +08002647 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002648 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002649 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002650 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002651
John Kessenichfc51d282015-08-19 13:34:18 -06002652 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002653 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2654 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2655 std::vector<spv::Id> arguments;
2656 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002657 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002658 else
2659 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002660 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002661
2662 spv::Builder::TextureParameters params = { };
2663 params.sampler = arguments[0];
2664
Rex Xu04db3f52015-09-16 11:44:02 +08002665 glslang::TCrackedTextureOp cracked;
2666 node->crackTexture(sampler, cracked);
2667
John Kessenichfc51d282015-08-19 13:34:18 -06002668 // Check for queries
2669 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002670 // a sampled image needs to have the image extracted first
2671 if (builder.isSampledImage(params.sampler))
2672 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002673 switch (node->getOp()) {
2674 case glslang::EOpImageQuerySize:
2675 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002676 if (arguments.size() > 1) {
2677 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002678 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002679 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002680 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002681 case glslang::EOpImageQuerySamples:
2682 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002683 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002684 case glslang::EOpTextureQueryLod:
2685 params.coords = arguments[1];
2686 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2687 case glslang::EOpTextureQueryLevels:
2688 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002689 case glslang::EOpSparseTexelsResident:
2690 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002691 default:
2692 assert(0);
2693 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002694 }
John Kessenich140f3df2015-06-26 16:58:36 -06002695 }
2696
Rex Xufc618912015-09-09 16:42:49 +08002697 // Check for image functions other than queries
2698 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002699 std::vector<spv::Id> operands;
2700 auto opIt = arguments.begin();
2701 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002702
2703 // Handle subpass operations
2704 // TODO: GLSL should change to have the "MS" only on the type rather than the
2705 // built-in function.
2706 if (cracked.subpass) {
2707 // add on the (0,0) coordinate
2708 spv::Id zero = builder.makeIntConstant(0);
2709 std::vector<spv::Id> comps;
2710 comps.push_back(zero);
2711 comps.push_back(zero);
2712 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2713 if (sampler.ms) {
2714 operands.push_back(spv::ImageOperandsSampleMask);
2715 operands.push_back(*(opIt++));
2716 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002717 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002718 }
2719
John Kessenich56bab042015-09-16 10:54:31 -06002720 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002721 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002722 if (sampler.ms) {
2723 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002724 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002725 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002726 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2727 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002728 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002729 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002730 if (sampler.ms) {
2731 operands.push_back(*(opIt + 1));
2732 operands.push_back(spv::ImageOperandsSampleMask);
2733 operands.push_back(*opIt);
2734 } else
2735 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002736 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002737 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2738 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002739 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002740 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2741 builder.addCapability(spv::CapabilitySparseResidency);
2742 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2743 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2744
2745 if (sampler.ms) {
2746 operands.push_back(spv::ImageOperandsSampleMask);
2747 operands.push_back(*opIt++);
2748 }
2749
2750 // Create the return type that was a special structure
2751 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002752 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002753 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2754 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2755
2756 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2757
2758 // Decode the return type
2759 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2760 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002761 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002762 // Process image atomic operations
2763
2764 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2765 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002766 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002767
John Kessenich8c8505c2016-07-26 12:50:38 -06002768 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002769 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002770
2771 std::vector<spv::Id> operands;
2772 operands.push_back(pointer);
2773 for (; opIt != arguments.end(); ++opIt)
2774 operands.push_back(*opIt);
2775
John Kessenich8c8505c2016-07-26 12:50:38 -06002776 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002777 }
2778 }
2779
2780 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002781 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002782 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2783
John Kessenichfc51d282015-08-19 13:34:18 -06002784 // check for bias argument
2785 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002786 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002787 int nonBiasArgCount = 2;
2788 if (cracked.offset)
2789 ++nonBiasArgCount;
2790 if (cracked.grad)
2791 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002792 if (cracked.lodClamp)
2793 ++nonBiasArgCount;
2794 if (sparse)
2795 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002796
2797 if ((int)arguments.size() > nonBiasArgCount)
2798 bias = true;
2799 }
2800
John Kessenicha5c33d62016-06-02 23:45:21 -06002801 // See if the sampler param should really be just the SPV image part
2802 if (cracked.fetch) {
2803 // a fetch needs to have the image extracted first
2804 if (builder.isSampledImage(params.sampler))
2805 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2806 }
2807
John Kessenichfc51d282015-08-19 13:34:18 -06002808 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002809
John Kessenichfc51d282015-08-19 13:34:18 -06002810 params.coords = arguments[1];
2811 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002812 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002813
2814 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002815 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002816 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002817 ++extraArgs;
2818 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002819 params.Dref = arguments[2];
2820 ++extraArgs;
2821 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002822 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002823 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002824 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002825 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002826 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002827 dRefComp = builder.getNumComponents(params.coords) - 1;
2828 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002829 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2830 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002831
2832 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002833 if (cracked.lod) {
2834 params.lod = arguments[2];
2835 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002836 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2837 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2838 noImplicitLod = true;
2839 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002840
2841 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002842 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002843 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002844 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002845 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002846
2847 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002848 if (cracked.grad) {
2849 params.gradX = arguments[2 + extraArgs];
2850 params.gradY = arguments[3 + extraArgs];
2851 extraArgs += 2;
2852 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002853
2854 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002855 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002856 params.offset = arguments[2 + extraArgs];
2857 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002858 } else if (cracked.offsets) {
2859 params.offsets = arguments[2 + extraArgs];
2860 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002861 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002862
2863 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002864 if (cracked.lodClamp) {
2865 params.lodClamp = arguments[2 + extraArgs];
2866 ++extraArgs;
2867 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002868
2869 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002870 if (sparse) {
2871 params.texelOut = arguments[2 + extraArgs];
2872 ++extraArgs;
2873 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002874
2875 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002876 if (bias) {
2877 params.bias = arguments[2 + extraArgs];
2878 ++extraArgs;
2879 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002880
2881 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002882 if (cracked.gather && ! sampler.shadow) {
2883 // default component is 0, if missing, otherwise an argument
2884 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002885 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002886 ++extraArgs;
2887 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002888 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002889 }
2890 }
John Kessenichfc51d282015-08-19 13:34:18 -06002891
John Kessenich65336482016-06-16 14:06:26 -06002892 // projective component (might not to move)
2893 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2894 // are divided by the last component of P."
2895 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2896 // unused components will appear after all used components."
2897 if (cracked.proj) {
2898 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2899 int projTargetComp;
2900 switch (sampler.dim) {
2901 case glslang::Esd1D: projTargetComp = 1; break;
2902 case glslang::Esd2D: projTargetComp = 2; break;
2903 case glslang::EsdRect: projTargetComp = 2; break;
2904 default: projTargetComp = projSourceComp; break;
2905 }
2906 // copy the projective coordinate if we have to
2907 if (projTargetComp != projSourceComp) {
2908 spv::Id projComp = builder.createCompositeExtract(params.coords,
2909 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2910 projSourceComp);
2911 params.coords = builder.createCompositeInsert(projComp, params.coords,
2912 builder.getTypeId(params.coords), projTargetComp);
2913 }
2914 }
2915
John Kessenich8c8505c2016-07-26 12:50:38 -06002916 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002917}
2918
2919spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2920{
2921 // Grab the function's pointer from the previously created function
2922 spv::Function* function = functionMap[node->getName().c_str()];
2923 if (! function)
2924 return 0;
2925
2926 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2927 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2928
2929 // See comments in makeFunctions() for details about the semantics for parameter passing.
2930 //
2931 // These imply we need a four step process:
2932 // 1. Evaluate the arguments
2933 // 2. Allocate and make copies of in, out, and inout arguments
2934 // 3. Make the call
2935 // 4. Copy back the results
2936
2937 // 1. Evaluate the arguments
2938 std::vector<spv::Builder::AccessChain> lValues;
2939 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002940 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002941 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002942 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002943 // build l-value
2944 builder.clearAccessChain();
2945 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002946 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06002947 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07002948 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002949 // save l-value
2950 lValues.push_back(builder.getAccessChain());
2951 } else {
2952 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002953 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002954 }
2955 }
2956
2957 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2958 // copy the original into that space.
2959 //
2960 // Also, build up the list of actual arguments to pass in for the call
2961 int lValueCount = 0;
2962 int rValueCount = 0;
2963 std::vector<spv::Id> spvArgs;
2964 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002965 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002966 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002967 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002968 builder.setAccessChain(lValues[lValueCount]);
2969 arg = builder.accessChainGetLValue();
2970 ++lValueCount;
2971 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002972 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002973 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2974 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2975 // need to copy the input into output space
2976 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002977 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06002978 builder.clearAccessChain();
2979 builder.setAccessChainLValue(arg);
2980 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002981 }
2982 ++lValueCount;
2983 } else {
2984 arg = rValues[rValueCount];
2985 ++rValueCount;
2986 }
2987 spvArgs.push_back(arg);
2988 }
2989
2990 // 3. Make the call.
2991 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002992 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002993
2994 // 4. Copy back out an "out" arguments.
2995 lValueCount = 0;
2996 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06002997 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002998 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2999 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3000 spv::Id copy = builder.createLoad(spvArgs[a]);
3001 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003002 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003003 }
3004 ++lValueCount;
3005 }
3006 }
3007
3008 return result;
3009}
3010
3011// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003012spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3013 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003014 spv::Id typeId, spv::Id left, spv::Id right,
3015 glslang::TBasicType typeProxy, bool reduceComparison)
3016{
Rex Xu8ff43de2016-04-22 16:51:45 +08003017 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003018 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08003019 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003020
3021 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003022 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003023 bool comparison = false;
3024
3025 switch (op) {
3026 case glslang::EOpAdd:
3027 case glslang::EOpAddAssign:
3028 if (isFloat)
3029 binOp = spv::OpFAdd;
3030 else
3031 binOp = spv::OpIAdd;
3032 break;
3033 case glslang::EOpSub:
3034 case glslang::EOpSubAssign:
3035 if (isFloat)
3036 binOp = spv::OpFSub;
3037 else
3038 binOp = spv::OpISub;
3039 break;
3040 case glslang::EOpMul:
3041 case glslang::EOpMulAssign:
3042 if (isFloat)
3043 binOp = spv::OpFMul;
3044 else
3045 binOp = spv::OpIMul;
3046 break;
3047 case glslang::EOpVectorTimesScalar:
3048 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003049 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003050 if (builder.isVector(right))
3051 std::swap(left, right);
3052 assert(builder.isScalar(right));
3053 needMatchingVectors = false;
3054 binOp = spv::OpVectorTimesScalar;
3055 } else
3056 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003057 break;
3058 case glslang::EOpVectorTimesMatrix:
3059 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003060 binOp = spv::OpVectorTimesMatrix;
3061 break;
3062 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003063 binOp = spv::OpMatrixTimesVector;
3064 break;
3065 case glslang::EOpMatrixTimesScalar:
3066 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003067 binOp = spv::OpMatrixTimesScalar;
3068 break;
3069 case glslang::EOpMatrixTimesMatrix:
3070 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003071 binOp = spv::OpMatrixTimesMatrix;
3072 break;
3073 case glslang::EOpOuterProduct:
3074 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003075 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003076 break;
3077
3078 case glslang::EOpDiv:
3079 case glslang::EOpDivAssign:
3080 if (isFloat)
3081 binOp = spv::OpFDiv;
3082 else if (isUnsigned)
3083 binOp = spv::OpUDiv;
3084 else
3085 binOp = spv::OpSDiv;
3086 break;
3087 case glslang::EOpMod:
3088 case glslang::EOpModAssign:
3089 if (isFloat)
3090 binOp = spv::OpFMod;
3091 else if (isUnsigned)
3092 binOp = spv::OpUMod;
3093 else
3094 binOp = spv::OpSMod;
3095 break;
3096 case glslang::EOpRightShift:
3097 case glslang::EOpRightShiftAssign:
3098 if (isUnsigned)
3099 binOp = spv::OpShiftRightLogical;
3100 else
3101 binOp = spv::OpShiftRightArithmetic;
3102 break;
3103 case glslang::EOpLeftShift:
3104 case glslang::EOpLeftShiftAssign:
3105 binOp = spv::OpShiftLeftLogical;
3106 break;
3107 case glslang::EOpAnd:
3108 case glslang::EOpAndAssign:
3109 binOp = spv::OpBitwiseAnd;
3110 break;
3111 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003112 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003113 binOp = spv::OpLogicalAnd;
3114 break;
3115 case glslang::EOpInclusiveOr:
3116 case glslang::EOpInclusiveOrAssign:
3117 binOp = spv::OpBitwiseOr;
3118 break;
3119 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003120 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003121 binOp = spv::OpLogicalOr;
3122 break;
3123 case glslang::EOpExclusiveOr:
3124 case glslang::EOpExclusiveOrAssign:
3125 binOp = spv::OpBitwiseXor;
3126 break;
3127 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003128 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003129 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003130 break;
3131
3132 case glslang::EOpLessThan:
3133 case glslang::EOpGreaterThan:
3134 case glslang::EOpLessThanEqual:
3135 case glslang::EOpGreaterThanEqual:
3136 case glslang::EOpEqual:
3137 case glslang::EOpNotEqual:
3138 case glslang::EOpVectorEqual:
3139 case glslang::EOpVectorNotEqual:
3140 comparison = true;
3141 break;
3142 default:
3143 break;
3144 }
3145
John Kessenich7c1aa102015-10-15 13:29:11 -06003146 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003147 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003148 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003149 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003150 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003151
3152 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003153 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003154 builder.promoteScalar(precision, left, right);
3155
qining25262b32016-05-06 17:25:16 -04003156 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3157 addDecoration(result, noContraction);
3158 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003159 }
3160
3161 if (! comparison)
3162 return 0;
3163
John Kessenich7c1aa102015-10-15 13:29:11 -06003164 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003165
John Kessenich4583b612016-08-07 19:14:22 -06003166 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3167 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003168 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003169
3170 switch (op) {
3171 case glslang::EOpLessThan:
3172 if (isFloat)
3173 binOp = spv::OpFOrdLessThan;
3174 else if (isUnsigned)
3175 binOp = spv::OpULessThan;
3176 else
3177 binOp = spv::OpSLessThan;
3178 break;
3179 case glslang::EOpGreaterThan:
3180 if (isFloat)
3181 binOp = spv::OpFOrdGreaterThan;
3182 else if (isUnsigned)
3183 binOp = spv::OpUGreaterThan;
3184 else
3185 binOp = spv::OpSGreaterThan;
3186 break;
3187 case glslang::EOpLessThanEqual:
3188 if (isFloat)
3189 binOp = spv::OpFOrdLessThanEqual;
3190 else if (isUnsigned)
3191 binOp = spv::OpULessThanEqual;
3192 else
3193 binOp = spv::OpSLessThanEqual;
3194 break;
3195 case glslang::EOpGreaterThanEqual:
3196 if (isFloat)
3197 binOp = spv::OpFOrdGreaterThanEqual;
3198 else if (isUnsigned)
3199 binOp = spv::OpUGreaterThanEqual;
3200 else
3201 binOp = spv::OpSGreaterThanEqual;
3202 break;
3203 case glslang::EOpEqual:
3204 case glslang::EOpVectorEqual:
3205 if (isFloat)
3206 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003207 else if (isBool)
3208 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003209 else
3210 binOp = spv::OpIEqual;
3211 break;
3212 case glslang::EOpNotEqual:
3213 case glslang::EOpVectorNotEqual:
3214 if (isFloat)
3215 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003216 else if (isBool)
3217 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003218 else
3219 binOp = spv::OpINotEqual;
3220 break;
3221 default:
3222 break;
3223 }
3224
qining25262b32016-05-06 17:25:16 -04003225 if (binOp != spv::OpNop) {
3226 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3227 addDecoration(result, noContraction);
3228 return builder.setPrecision(result, precision);
3229 }
John Kessenich140f3df2015-06-26 16:58:36 -06003230
3231 return 0;
3232}
3233
John Kessenich04bb8a02015-12-12 12:28:14 -07003234//
3235// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3236// These can be any of:
3237//
3238// matrix * scalar
3239// scalar * matrix
3240// matrix * matrix linear algebraic
3241// matrix * vector
3242// vector * matrix
3243// matrix * matrix componentwise
3244// matrix op matrix op in {+, -, /}
3245// matrix op scalar op in {+, -, /}
3246// scalar op matrix op in {+, -, /}
3247//
qining25262b32016-05-06 17:25:16 -04003248spv::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 -07003249{
3250 bool firstClass = true;
3251
3252 // First, handle first-class matrix operations (* and matrix/scalar)
3253 switch (op) {
3254 case spv::OpFDiv:
3255 if (builder.isMatrix(left) && builder.isScalar(right)) {
3256 // turn matrix / scalar into a multiply...
3257 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3258 op = spv::OpMatrixTimesScalar;
3259 } else
3260 firstClass = false;
3261 break;
3262 case spv::OpMatrixTimesScalar:
3263 if (builder.isMatrix(right))
3264 std::swap(left, right);
3265 assert(builder.isScalar(right));
3266 break;
3267 case spv::OpVectorTimesMatrix:
3268 assert(builder.isVector(left));
3269 assert(builder.isMatrix(right));
3270 break;
3271 case spv::OpMatrixTimesVector:
3272 assert(builder.isMatrix(left));
3273 assert(builder.isVector(right));
3274 break;
3275 case spv::OpMatrixTimesMatrix:
3276 assert(builder.isMatrix(left));
3277 assert(builder.isMatrix(right));
3278 break;
3279 default:
3280 firstClass = false;
3281 break;
3282 }
3283
qining25262b32016-05-06 17:25:16 -04003284 if (firstClass) {
3285 spv::Id result = builder.createBinOp(op, typeId, left, right);
3286 addDecoration(result, noContraction);
3287 return builder.setPrecision(result, precision);
3288 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003289
LoopDawg592860c2016-06-09 08:57:35 -06003290 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003291 // The result type of all of them is the same type as the (a) matrix operand.
3292 // The algorithm is to:
3293 // - break the matrix(es) into vectors
3294 // - smear any scalar to a vector
3295 // - do vector operations
3296 // - make a matrix out the vector results
3297 switch (op) {
3298 case spv::OpFAdd:
3299 case spv::OpFSub:
3300 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003301 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003302 case spv::OpFMul:
3303 {
3304 // one time set up...
3305 bool leftMat = builder.isMatrix(left);
3306 bool rightMat = builder.isMatrix(right);
3307 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3308 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3309 spv::Id scalarType = builder.getScalarTypeId(typeId);
3310 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3311 std::vector<spv::Id> results;
3312 spv::Id smearVec = spv::NoResult;
3313 if (builder.isScalar(left))
3314 smearVec = builder.smearScalar(precision, left, vecType);
3315 else if (builder.isScalar(right))
3316 smearVec = builder.smearScalar(precision, right, vecType);
3317
3318 // do each vector op
3319 for (unsigned int c = 0; c < numCols; ++c) {
3320 std::vector<unsigned int> indexes;
3321 indexes.push_back(c);
3322 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3323 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003324 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3325 addDecoration(result, noContraction);
3326 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003327 }
3328
3329 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003330 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003331 }
3332 default:
3333 assert(0);
3334 return spv::NoResult;
3335 }
3336}
3337
qining25262b32016-05-06 17:25:16 -04003338spv::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 -06003339{
3340 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003341 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003342 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003343 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003344 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003345
3346 switch (op) {
3347 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003348 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003349 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003350 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003351 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003352 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003353 unaryOp = spv::OpSNegate;
3354 break;
3355
3356 case glslang::EOpLogicalNot:
3357 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003358 unaryOp = spv::OpLogicalNot;
3359 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003360 case glslang::EOpBitwiseNot:
3361 unaryOp = spv::OpNot;
3362 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003363
John Kessenich140f3df2015-06-26 16:58:36 -06003364 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003365 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003366 break;
3367 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003368 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003369 break;
3370 case glslang::EOpTranspose:
3371 unaryOp = spv::OpTranspose;
3372 break;
3373
3374 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003375 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003376 break;
3377 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003378 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003379 break;
3380 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003381 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003382 break;
3383 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003384 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003385 break;
3386 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003387 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003388 break;
3389 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003390 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003391 break;
3392 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003393 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003394 break;
3395 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003396 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003397 break;
3398
3399 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003400 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003401 break;
3402 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003403 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003404 break;
3405 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003406 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003407 break;
3408 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003409 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003410 break;
3411 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003412 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003413 break;
3414 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003415 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003416 break;
3417
3418 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003419 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003420 break;
3421 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003422 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003423 break;
3424
3425 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003426 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003427 break;
3428 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003429 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003430 break;
3431 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003432 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003433 break;
3434 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003435 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003436 break;
3437 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003438 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003439 break;
3440 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003441 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003442 break;
3443
3444 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003445 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003446 break;
3447 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003448 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003449 break;
3450 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003451 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003452 break;
3453 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003454 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003455 break;
3456 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003457 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003458 break;
3459 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003460 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003461 break;
3462
3463 case glslang::EOpIsNan:
3464 unaryOp = spv::OpIsNan;
3465 break;
3466 case glslang::EOpIsInf:
3467 unaryOp = spv::OpIsInf;
3468 break;
LoopDawg592860c2016-06-09 08:57:35 -06003469 case glslang::EOpIsFinite:
3470 unaryOp = spv::OpIsFinite;
3471 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003472
Rex Xucbc426e2015-12-15 16:03:10 +08003473 case glslang::EOpFloatBitsToInt:
3474 case glslang::EOpFloatBitsToUint:
3475 case glslang::EOpIntBitsToFloat:
3476 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003477 case glslang::EOpDoubleBitsToInt64:
3478 case glslang::EOpDoubleBitsToUint64:
3479 case glslang::EOpInt64BitsToDouble:
3480 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003481 unaryOp = spv::OpBitcast;
3482 break;
3483
John Kessenich140f3df2015-06-26 16:58:36 -06003484 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003485 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003486 break;
3487 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003488 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003489 break;
3490 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003491 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003492 break;
3493 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003494 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003495 break;
3496 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003497 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003498 break;
3499 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003500 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003501 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003502 case glslang::EOpPackSnorm4x8:
3503 libCall = spv::GLSLstd450PackSnorm4x8;
3504 break;
3505 case glslang::EOpUnpackSnorm4x8:
3506 libCall = spv::GLSLstd450UnpackSnorm4x8;
3507 break;
3508 case glslang::EOpPackUnorm4x8:
3509 libCall = spv::GLSLstd450PackUnorm4x8;
3510 break;
3511 case glslang::EOpUnpackUnorm4x8:
3512 libCall = spv::GLSLstd450UnpackUnorm4x8;
3513 break;
3514 case glslang::EOpPackDouble2x32:
3515 libCall = spv::GLSLstd450PackDouble2x32;
3516 break;
3517 case glslang::EOpUnpackDouble2x32:
3518 libCall = spv::GLSLstd450UnpackDouble2x32;
3519 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003520
Rex Xu8ff43de2016-04-22 16:51:45 +08003521 case glslang::EOpPackInt2x32:
3522 case glslang::EOpUnpackInt2x32:
3523 case glslang::EOpPackUint2x32:
3524 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003525 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003526 break;
3527
John Kessenich140f3df2015-06-26 16:58:36 -06003528 case glslang::EOpDPdx:
3529 unaryOp = spv::OpDPdx;
3530 break;
3531 case glslang::EOpDPdy:
3532 unaryOp = spv::OpDPdy;
3533 break;
3534 case glslang::EOpFwidth:
3535 unaryOp = spv::OpFwidth;
3536 break;
3537 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003538 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003539 unaryOp = spv::OpDPdxFine;
3540 break;
3541 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003542 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003543 unaryOp = spv::OpDPdyFine;
3544 break;
3545 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003546 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003547 unaryOp = spv::OpFwidthFine;
3548 break;
3549 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003550 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003551 unaryOp = spv::OpDPdxCoarse;
3552 break;
3553 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003554 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003555 unaryOp = spv::OpDPdyCoarse;
3556 break;
3557 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003558 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003559 unaryOp = spv::OpFwidthCoarse;
3560 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003561 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003562 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003563 libCall = spv::GLSLstd450InterpolateAtCentroid;
3564 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003565 case glslang::EOpAny:
3566 unaryOp = spv::OpAny;
3567 break;
3568 case glslang::EOpAll:
3569 unaryOp = spv::OpAll;
3570 break;
3571
3572 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003573 if (isFloat)
3574 libCall = spv::GLSLstd450FAbs;
3575 else
3576 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003577 break;
3578 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003579 if (isFloat)
3580 libCall = spv::GLSLstd450FSign;
3581 else
3582 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003583 break;
3584
John Kessenichfc51d282015-08-19 13:34:18 -06003585 case glslang::EOpAtomicCounterIncrement:
3586 case glslang::EOpAtomicCounterDecrement:
3587 case glslang::EOpAtomicCounter:
3588 {
3589 // Handle all of the atomics in one place, in createAtomicOperation()
3590 std::vector<spv::Id> operands;
3591 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003592 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003593 }
3594
John Kessenichfc51d282015-08-19 13:34:18 -06003595 case glslang::EOpBitFieldReverse:
3596 unaryOp = spv::OpBitReverse;
3597 break;
3598 case glslang::EOpBitCount:
3599 unaryOp = spv::OpBitCount;
3600 break;
3601 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003602 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003603 break;
3604 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003605 if (isUnsigned)
3606 libCall = spv::GLSLstd450FindUMsb;
3607 else
3608 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003609 break;
3610
Rex Xu574ab042016-04-14 16:53:07 +08003611 case glslang::EOpBallot:
3612 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003613 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003614 libCall = spv::GLSLstd450Bad;
3615 break;
3616
Rex Xu338b1852016-05-05 20:38:33 +08003617 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003618 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003619 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003620#ifdef AMD_EXTENSIONS
3621 case glslang::EOpMinInvocations:
3622 case glslang::EOpMaxInvocations:
3623 case glslang::EOpAddInvocations:
3624 case glslang::EOpMinInvocationsNonUniform:
3625 case glslang::EOpMaxInvocationsNonUniform:
3626 case glslang::EOpAddInvocationsNonUniform:
3627#endif
3628 return createInvocationsOperation(op, typeId, operand, typeProxy);
3629
3630#ifdef AMD_EXTENSIONS
3631 case glslang::EOpMbcnt:
3632 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3633 libCall = spv::MbcntAMD;
3634 break;
3635
3636 case glslang::EOpCubeFaceIndex:
3637 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3638 libCall = spv::CubeFaceIndexAMD;
3639 break;
3640
3641 case glslang::EOpCubeFaceCoord:
3642 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3643 libCall = spv::CubeFaceCoordAMD;
3644 break;
3645#endif
Rex Xu338b1852016-05-05 20:38:33 +08003646
John Kessenich140f3df2015-06-26 16:58:36 -06003647 default:
3648 return 0;
3649 }
3650
3651 spv::Id id;
3652 if (libCall >= 0) {
3653 std::vector<spv::Id> args;
3654 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003655 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003656 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003657 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003658 }
John Kessenich140f3df2015-06-26 16:58:36 -06003659
qining25262b32016-05-06 17:25:16 -04003660 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003661 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003662}
3663
John Kessenich7a53f762016-01-20 11:19:27 -07003664// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003665spv::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 -07003666{
3667 // Handle unary operations vector by vector.
3668 // The result type is the same type as the original type.
3669 // The algorithm is to:
3670 // - break the matrix into vectors
3671 // - apply the operation to each vector
3672 // - make a matrix out the vector results
3673
3674 // get the types sorted out
3675 int numCols = builder.getNumColumns(operand);
3676 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003677 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3678 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003679 std::vector<spv::Id> results;
3680
3681 // do each vector op
3682 for (int c = 0; c < numCols; ++c) {
3683 std::vector<unsigned int> indexes;
3684 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003685 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3686 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3687 addDecoration(destVec, noContraction);
3688 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003689 }
3690
3691 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003692 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003693}
3694
Rex Xu73e3ce72016-04-27 18:48:17 +08003695spv::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 -06003696{
3697 spv::Op convOp = spv::OpNop;
3698 spv::Id zero = 0;
3699 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003700 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003701
3702 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3703
3704 switch (op) {
3705 case glslang::EOpConvIntToBool:
3706 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003707 case glslang::EOpConvInt64ToBool:
3708 case glslang::EOpConvUint64ToBool:
3709 zero = (op == glslang::EOpConvInt64ToBool ||
3710 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003711 zero = makeSmearedConstant(zero, vectorSize);
3712 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3713
3714 case glslang::EOpConvFloatToBool:
3715 zero = builder.makeFloatConstant(0.0F);
3716 zero = makeSmearedConstant(zero, vectorSize);
3717 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3718
3719 case glslang::EOpConvDoubleToBool:
3720 zero = builder.makeDoubleConstant(0.0);
3721 zero = makeSmearedConstant(zero, vectorSize);
3722 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3723
3724 case glslang::EOpConvBoolToFloat:
3725 convOp = spv::OpSelect;
3726 zero = builder.makeFloatConstant(0.0);
3727 one = builder.makeFloatConstant(1.0);
3728 break;
3729 case glslang::EOpConvBoolToDouble:
3730 convOp = spv::OpSelect;
3731 zero = builder.makeDoubleConstant(0.0);
3732 one = builder.makeDoubleConstant(1.0);
3733 break;
3734 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003735 case glslang::EOpConvBoolToInt64:
3736 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3737 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003738 convOp = spv::OpSelect;
3739 break;
3740 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003741 case glslang::EOpConvBoolToUint64:
3742 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3743 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003744 convOp = spv::OpSelect;
3745 break;
3746
3747 case glslang::EOpConvIntToFloat:
3748 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003749 case glslang::EOpConvInt64ToFloat:
3750 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003751 convOp = spv::OpConvertSToF;
3752 break;
3753
3754 case glslang::EOpConvUintToFloat:
3755 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003756 case glslang::EOpConvUint64ToFloat:
3757 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003758 convOp = spv::OpConvertUToF;
3759 break;
3760
3761 case glslang::EOpConvDoubleToFloat:
3762 case glslang::EOpConvFloatToDouble:
3763 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003764 if (builder.isMatrixType(destType))
3765 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003766 break;
3767
3768 case glslang::EOpConvFloatToInt:
3769 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003770 case glslang::EOpConvFloatToInt64:
3771 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003772 convOp = spv::OpConvertFToS;
3773 break;
3774
3775 case glslang::EOpConvUintToInt:
3776 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003777 case glslang::EOpConvUint64ToInt64:
3778 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003779 if (builder.isInSpecConstCodeGenMode()) {
3780 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08003781 zero = (op == glslang::EOpConvUint64ToInt64 ||
3782 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003783 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003784 // Use OpIAdd, instead of OpBitcast to do the conversion when
3785 // generating for OpSpecConstantOp instruction.
3786 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3787 }
3788 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003789 convOp = spv::OpBitcast;
3790 break;
3791
3792 case glslang::EOpConvFloatToUint:
3793 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003794 case glslang::EOpConvFloatToUint64:
3795 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003796 convOp = spv::OpConvertFToU;
3797 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003798
3799 case glslang::EOpConvIntToInt64:
3800 case glslang::EOpConvInt64ToInt:
3801 convOp = spv::OpSConvert;
3802 break;
3803
3804 case glslang::EOpConvUintToUint64:
3805 case glslang::EOpConvUint64ToUint:
3806 convOp = spv::OpUConvert;
3807 break;
3808
3809 case glslang::EOpConvIntToUint64:
3810 case glslang::EOpConvInt64ToUint:
3811 case glslang::EOpConvUint64ToInt:
3812 case glslang::EOpConvUintToInt64:
3813 // OpSConvert/OpUConvert + OpBitCast
3814 switch (op) {
3815 case glslang::EOpConvIntToUint64:
3816 convOp = spv::OpSConvert;
3817 type = builder.makeIntType(64);
3818 break;
3819 case glslang::EOpConvInt64ToUint:
3820 convOp = spv::OpSConvert;
3821 type = builder.makeIntType(32);
3822 break;
3823 case glslang::EOpConvUint64ToInt:
3824 convOp = spv::OpUConvert;
3825 type = builder.makeUintType(32);
3826 break;
3827 case glslang::EOpConvUintToInt64:
3828 convOp = spv::OpUConvert;
3829 type = builder.makeUintType(64);
3830 break;
3831 default:
3832 assert(0);
3833 break;
3834 }
3835
3836 if (vectorSize > 0)
3837 type = builder.makeVectorType(type, vectorSize);
3838
3839 operand = builder.createUnaryOp(convOp, type, operand);
3840
3841 if (builder.isInSpecConstCodeGenMode()) {
3842 // Build zero scalar or vector for OpIAdd.
3843 zero = (op == glslang::EOpConvIntToUint64 ||
3844 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3845 zero = makeSmearedConstant(zero, vectorSize);
3846 // Use OpIAdd, instead of OpBitcast to do the conversion when
3847 // generating for OpSpecConstantOp instruction.
3848 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3849 }
3850 // For normal run-time conversion instruction, use OpBitcast.
3851 convOp = spv::OpBitcast;
3852 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003853 default:
3854 break;
3855 }
3856
3857 spv::Id result = 0;
3858 if (convOp == spv::OpNop)
3859 return result;
3860
3861 if (convOp == spv::OpSelect) {
3862 zero = makeSmearedConstant(zero, vectorSize);
3863 one = makeSmearedConstant(one, vectorSize);
3864 result = builder.createTriOp(convOp, destType, operand, one, zero);
3865 } else
3866 result = builder.createUnaryOp(convOp, destType, operand);
3867
John Kessenich32cfd492016-02-02 12:37:46 -07003868 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003869}
3870
3871spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3872{
3873 if (vectorSize == 0)
3874 return constant;
3875
3876 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3877 std::vector<spv::Id> components;
3878 for (int c = 0; c < vectorSize; ++c)
3879 components.push_back(constant);
3880 return builder.makeCompositeConstant(vectorTypeId, components);
3881}
3882
John Kessenich426394d2015-07-23 10:22:48 -06003883// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003884spv::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 -06003885{
3886 spv::Op opCode = spv::OpNop;
3887
3888 switch (op) {
3889 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003890 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003891 opCode = spv::OpAtomicIAdd;
3892 break;
3893 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003894 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003895 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003896 break;
3897 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003898 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003899 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003900 break;
3901 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003902 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003903 opCode = spv::OpAtomicAnd;
3904 break;
3905 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003906 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003907 opCode = spv::OpAtomicOr;
3908 break;
3909 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003910 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003911 opCode = spv::OpAtomicXor;
3912 break;
3913 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003914 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003915 opCode = spv::OpAtomicExchange;
3916 break;
3917 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003918 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003919 opCode = spv::OpAtomicCompareExchange;
3920 break;
3921 case glslang::EOpAtomicCounterIncrement:
3922 opCode = spv::OpAtomicIIncrement;
3923 break;
3924 case glslang::EOpAtomicCounterDecrement:
3925 opCode = spv::OpAtomicIDecrement;
3926 break;
3927 case glslang::EOpAtomicCounter:
3928 opCode = spv::OpAtomicLoad;
3929 break;
3930 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003931 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003932 break;
3933 }
3934
3935 // Sort out the operands
3936 // - mapping from glslang -> SPV
3937 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003938 // - compare-exchange swaps the value and comparator
3939 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003940 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3941 auto opIt = operands.begin(); // walk the glslang operands
3942 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003943 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3944 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3945 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003946 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3947 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003948 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003949 spvAtomicOperands.push_back(*(opIt + 1));
3950 spvAtomicOperands.push_back(*opIt);
3951 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003952 }
John Kessenich426394d2015-07-23 10:22:48 -06003953
John Kessenich3e60a6f2015-09-14 22:45:16 -06003954 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003955 for (; opIt != operands.end(); ++opIt)
3956 spvAtomicOperands.push_back(*opIt);
3957
3958 return builder.createOp(opCode, typeId, spvAtomicOperands);
3959}
3960
John Kessenich91cef522016-05-05 16:45:40 -06003961// Create group invocation operations.
Rex Xu9d93a232016-05-05 12:30:44 +08003962spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06003963{
Rex Xu9d93a232016-05-05 12:30:44 +08003964 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
3965 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3966
John Kessenich91cef522016-05-05 16:45:40 -06003967 builder.addCapability(spv::CapabilityGroups);
3968
3969 std::vector<spv::Id> operands;
3970 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08003971#ifdef AMD_EXTENSIONS
3972 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
3973 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
3974 operands.push_back(spv::GroupOperationReduce);
3975#endif
John Kessenich91cef522016-05-05 16:45:40 -06003976 operands.push_back(operand);
3977
3978 switch (op) {
3979 case glslang::EOpAnyInvocation:
3980 case glslang::EOpAllInvocations:
3981 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3982
3983 case glslang::EOpAllInvocationsEqual:
3984 {
3985 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3986 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3987
3988 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3989 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3990 }
Rex Xu9d93a232016-05-05 12:30:44 +08003991#ifdef AMD_EXTENSIONS
3992 case glslang::EOpMinInvocations:
3993 case glslang::EOpMaxInvocations:
3994 case glslang::EOpAddInvocations:
3995 {
3996 spv::Op spvOp = spv::OpNop;
3997 if (op == glslang::EOpMinInvocations) {
3998 if (isFloat)
3999 spvOp = spv::OpGroupFMin;
4000 else {
4001 if (isUnsigned)
4002 spvOp = spv::OpGroupUMin;
4003 else
4004 spvOp = spv::OpGroupSMin;
4005 }
4006 } else if (op == glslang::EOpMaxInvocations) {
4007 if (isFloat)
4008 spvOp = spv::OpGroupFMax;
4009 else {
4010 if (isUnsigned)
4011 spvOp = spv::OpGroupUMax;
4012 else
4013 spvOp = spv::OpGroupSMax;
4014 }
4015 } else {
4016 if (isFloat)
4017 spvOp = spv::OpGroupFAdd;
4018 else
4019 spvOp = spv::OpGroupIAdd;
4020 }
4021
Rex Xu2bbbe062016-08-23 15:41:05 +08004022 if (builder.isVectorType(typeId))
4023 return CreateInvocationsVectorOperation(spvOp, typeId, operand);
4024 else
4025 return builder.createOp(spvOp, typeId, operands);
Rex Xu9d93a232016-05-05 12:30:44 +08004026 }
4027 case glslang::EOpMinInvocationsNonUniform:
4028 case glslang::EOpMaxInvocationsNonUniform:
4029 case glslang::EOpAddInvocationsNonUniform:
4030 {
4031 spv::Op spvOp = spv::OpNop;
4032 if (op == glslang::EOpMinInvocationsNonUniform) {
4033 if (isFloat)
4034 spvOp = spv::OpGroupFMinNonUniformAMD;
4035 else {
4036 if (isUnsigned)
4037 spvOp = spv::OpGroupUMinNonUniformAMD;
4038 else
4039 spvOp = spv::OpGroupSMinNonUniformAMD;
4040 }
4041 }
4042 else if (op == glslang::EOpMaxInvocationsNonUniform) {
4043 if (isFloat)
4044 spvOp = spv::OpGroupFMaxNonUniformAMD;
4045 else {
4046 if (isUnsigned)
4047 spvOp = spv::OpGroupUMaxNonUniformAMD;
4048 else
4049 spvOp = spv::OpGroupSMaxNonUniformAMD;
4050 }
4051 }
4052 else {
4053 if (isFloat)
4054 spvOp = spv::OpGroupFAddNonUniformAMD;
4055 else
4056 spvOp = spv::OpGroupIAddNonUniformAMD;
4057 }
4058
Rex Xu2bbbe062016-08-23 15:41:05 +08004059 if (builder.isVectorType(typeId))
4060 return CreateInvocationsVectorOperation(spvOp, typeId, operand);
4061 else
4062 return builder.createOp(spvOp, typeId, operands);
Rex Xu9d93a232016-05-05 12:30:44 +08004063 }
4064#endif
John Kessenich91cef522016-05-05 16:45:40 -06004065 default:
4066 logger->missingFunctionality("invocation operation");
4067 return spv::NoResult;
4068 }
4069}
4070
Rex Xu2bbbe062016-08-23 15:41:05 +08004071#ifdef AMD_EXTENSIONS
4072// Create group invocation operations on a vector
4073spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, spv::Id operand)
4074{
4075 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4076 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
4077 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd ||
4078 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4079 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4080 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
4081
4082 // Handle group invocation operations scalar by scalar.
4083 // The result type is the same type as the original type.
4084 // The algorithm is to:
4085 // - break the vector into scalars
4086 // - apply the operation to each scalar
4087 // - make a vector out the scalar results
4088
4089 // get the types sorted out
4090 int numComponents = builder.getNumComponents(operand);
4091 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operand));
4092 std::vector<spv::Id> results;
4093
4094 // do each scalar op
4095 for (int comp = 0; comp < numComponents; ++comp) {
4096 std::vector<unsigned int> indexes;
4097 indexes.push_back(comp);
4098 spv::Id scalar = builder.createCompositeExtract(operand, scalarType, indexes);
4099
4100 std::vector<spv::Id> operands;
4101 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
4102 operands.push_back(spv::GroupOperationReduce);
4103 operands.push_back(scalar);
4104
4105 results.push_back(builder.createOp(op, scalarType, operands));
4106 }
4107
4108 // put the pieces together
4109 return builder.createCompositeConstruct(typeId, results);
4110}
4111#endif
4112
John Kessenich5e4b1242015-08-06 22:53:06 -06004113spv::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 -06004114{
Rex Xu8ff43de2016-04-22 16:51:45 +08004115 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06004116 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
4117
John Kessenich140f3df2015-06-26 16:58:36 -06004118 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004119 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004120 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004121 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004122 spv::Id typeId0 = 0;
4123 if (consumedOperands > 0)
4124 typeId0 = builder.getTypeId(operands[0]);
4125 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004126
4127 switch (op) {
4128 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004129 if (isFloat)
4130 libCall = spv::GLSLstd450FMin;
4131 else if (isUnsigned)
4132 libCall = spv::GLSLstd450UMin;
4133 else
4134 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004135 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004136 break;
4137 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004138 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004139 break;
4140 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004141 if (isFloat)
4142 libCall = spv::GLSLstd450FMax;
4143 else if (isUnsigned)
4144 libCall = spv::GLSLstd450UMax;
4145 else
4146 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004147 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004148 break;
4149 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004150 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004151 break;
4152 case glslang::EOpDot:
4153 opCode = spv::OpDot;
4154 break;
4155 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004156 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004157 break;
4158
4159 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004160 if (isFloat)
4161 libCall = spv::GLSLstd450FClamp;
4162 else if (isUnsigned)
4163 libCall = spv::GLSLstd450UClamp;
4164 else
4165 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004166 builder.promoteScalar(precision, operands.front(), operands[1]);
4167 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004168 break;
4169 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004170 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4171 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004172 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004173 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004174 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004175 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004176 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004177 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004178 break;
4179 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004180 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004181 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004182 break;
4183 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004184 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004185 builder.promoteScalar(precision, operands[0], operands[2]);
4186 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004187 break;
4188
4189 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004190 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004191 break;
4192 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004193 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004194 break;
4195 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004196 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004197 break;
4198 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004199 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004200 break;
4201 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004202 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004203 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004204 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004205 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004206 libCall = spv::GLSLstd450InterpolateAtSample;
4207 break;
4208 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004209 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004210 libCall = spv::GLSLstd450InterpolateAtOffset;
4211 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004212 case glslang::EOpAddCarry:
4213 opCode = spv::OpIAddCarry;
4214 typeId = builder.makeStructResultType(typeId0, typeId0);
4215 consumedOperands = 2;
4216 break;
4217 case glslang::EOpSubBorrow:
4218 opCode = spv::OpISubBorrow;
4219 typeId = builder.makeStructResultType(typeId0, typeId0);
4220 consumedOperands = 2;
4221 break;
4222 case glslang::EOpUMulExtended:
4223 opCode = spv::OpUMulExtended;
4224 typeId = builder.makeStructResultType(typeId0, typeId0);
4225 consumedOperands = 2;
4226 break;
4227 case glslang::EOpIMulExtended:
4228 opCode = spv::OpSMulExtended;
4229 typeId = builder.makeStructResultType(typeId0, typeId0);
4230 consumedOperands = 2;
4231 break;
4232 case glslang::EOpBitfieldExtract:
4233 if (isUnsigned)
4234 opCode = spv::OpBitFieldUExtract;
4235 else
4236 opCode = spv::OpBitFieldSExtract;
4237 break;
4238 case glslang::EOpBitfieldInsert:
4239 opCode = spv::OpBitFieldInsert;
4240 break;
4241
4242 case glslang::EOpFma:
4243 libCall = spv::GLSLstd450Fma;
4244 break;
4245 case glslang::EOpFrexp:
4246 libCall = spv::GLSLstd450FrexpStruct;
4247 if (builder.getNumComponents(operands[0]) == 1)
4248 frexpIntType = builder.makeIntegerType(32, true);
4249 else
4250 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4251 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4252 consumedOperands = 1;
4253 break;
4254 case glslang::EOpLdexp:
4255 libCall = spv::GLSLstd450Ldexp;
4256 break;
4257
Rex Xu574ab042016-04-14 16:53:07 +08004258 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06004259 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08004260 libCall = spv::GLSLstd450Bad;
4261 break;
4262
Rex Xu9d93a232016-05-05 12:30:44 +08004263#ifdef AMD_EXTENSIONS
4264 case glslang::EOpSwizzleInvocations:
4265 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4266 libCall = spv::SwizzleInvocationsAMD;
4267 break;
4268 case glslang::EOpSwizzleInvocationsMasked:
4269 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4270 libCall = spv::SwizzleInvocationsMaskedAMD;
4271 break;
4272 case glslang::EOpWriteInvocation:
4273 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4274 libCall = spv::WriteInvocationAMD;
4275 break;
4276
4277 case glslang::EOpMin3:
4278 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4279 if (isFloat)
4280 libCall = spv::FMin3AMD;
4281 else {
4282 if (isUnsigned)
4283 libCall = spv::UMin3AMD;
4284 else
4285 libCall = spv::SMin3AMD;
4286 }
4287 break;
4288 case glslang::EOpMax3:
4289 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4290 if (isFloat)
4291 libCall = spv::FMax3AMD;
4292 else {
4293 if (isUnsigned)
4294 libCall = spv::UMax3AMD;
4295 else
4296 libCall = spv::SMax3AMD;
4297 }
4298 break;
4299 case glslang::EOpMid3:
4300 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4301 if (isFloat)
4302 libCall = spv::FMid3AMD;
4303 else {
4304 if (isUnsigned)
4305 libCall = spv::UMid3AMD;
4306 else
4307 libCall = spv::SMid3AMD;
4308 }
4309 break;
4310
4311 case glslang::EOpInterpolateAtVertex:
4312 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4313 libCall = spv::InterpolateAtVertexAMD;
4314 break;
4315#endif
4316
John Kessenich140f3df2015-06-26 16:58:36 -06004317 default:
4318 return 0;
4319 }
4320
4321 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004322 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004323 // Use an extended instruction from the standard library.
4324 // Construct the call arguments, without modifying the original operands vector.
4325 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4326 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004327 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004328 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004329 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004330 case 0:
4331 // should all be handled by visitAggregate and createNoArgOperation
4332 assert(0);
4333 return 0;
4334 case 1:
4335 // should all be handled by createUnaryOperation
4336 assert(0);
4337 return 0;
4338 case 2:
4339 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4340 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004341 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004342 // anything 3 or over doesn't have l-value operands, so all should be consumed
4343 assert(consumedOperands == operands.size());
4344 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004345 break;
4346 }
4347 }
4348
John Kessenich55e7d112015-11-15 21:33:39 -07004349 // Decode the return types that were structures
4350 switch (op) {
4351 case glslang::EOpAddCarry:
4352 case glslang::EOpSubBorrow:
4353 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4354 id = builder.createCompositeExtract(id, typeId0, 0);
4355 break;
4356 case glslang::EOpUMulExtended:
4357 case glslang::EOpIMulExtended:
4358 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4359 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4360 break;
4361 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004362 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004363 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4364 id = builder.createCompositeExtract(id, typeId0, 0);
4365 break;
4366 default:
4367 break;
4368 }
4369
John Kessenich32cfd492016-02-02 12:37:46 -07004370 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004371}
4372
Rex Xu9d93a232016-05-05 12:30:44 +08004373// Intrinsics with no arguments (or no return value, and no precision).
4374spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004375{
4376 // TODO: get the barrier operands correct
4377
4378 switch (op) {
4379 case glslang::EOpEmitVertex:
4380 builder.createNoResultOp(spv::OpEmitVertex);
4381 return 0;
4382 case glslang::EOpEndPrimitive:
4383 builder.createNoResultOp(spv::OpEndPrimitive);
4384 return 0;
4385 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004386 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004387 return 0;
4388 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004389 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004390 return 0;
4391 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004392 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004393 return 0;
4394 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004395 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004396 return 0;
4397 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004398 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004399 return 0;
4400 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004401 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004402 return 0;
4403 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004404 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004405 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004406 case glslang::EOpAllMemoryBarrierWithGroupSync:
4407 // Control barrier with non-"None" semantic is also a memory barrier.
4408 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4409 return 0;
4410 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4411 // Control barrier with non-"None" semantic is also a memory barrier.
4412 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4413 return 0;
4414 case glslang::EOpWorkgroupMemoryBarrier:
4415 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4416 return 0;
4417 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4418 // Control barrier with non-"None" semantic is also a memory barrier.
4419 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4420 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004421#ifdef AMD_EXTENSIONS
4422 case glslang::EOpTime:
4423 {
4424 std::vector<spv::Id> args; // Dummy arguments
4425 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4426 return builder.setPrecision(id, precision);
4427 }
4428#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004429 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004430 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004431 return 0;
4432 }
4433}
4434
4435spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4436{
John Kessenich2f273362015-07-18 22:34:27 -06004437 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004438 spv::Id id;
4439 if (symbolValues.end() != iter) {
4440 id = iter->second;
4441 return id;
4442 }
4443
4444 // it was not found, create it
4445 id = createSpvVariable(symbol);
4446 symbolValues[symbol->getId()] = id;
4447
Rex Xuc884b4a2016-06-29 15:03:44 +08004448 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004449 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004450 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004451 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004452 if (symbol->getType().getQualifier().hasSpecConstantId())
4453 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004454 if (symbol->getQualifier().hasIndex())
4455 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4456 if (symbol->getQualifier().hasComponent())
4457 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4458 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004459 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004460 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004461 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004462 if (symbol->getQualifier().hasXfbBuffer())
4463 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4464 if (symbol->getQualifier().hasXfbOffset())
4465 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4466 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004467 // atomic counters use this:
4468 if (symbol->getQualifier().hasOffset())
4469 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004470 }
4471
scygan2c864272016-05-18 18:09:17 +02004472 if (symbol->getQualifier().hasLocation())
4473 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004474 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004475 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004476 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004477 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004478 }
John Kessenich140f3df2015-06-26 16:58:36 -06004479 if (symbol->getQualifier().hasSet())
4480 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004481 else if (IsDescriptorResource(symbol->getType())) {
4482 // default to 0
4483 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4484 }
John Kessenich140f3df2015-06-26 16:58:36 -06004485 if (symbol->getQualifier().hasBinding())
4486 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004487 if (symbol->getQualifier().hasAttachment())
4488 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004489 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004490 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004491 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004492 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004493 if (symbol->getQualifier().hasXfbBuffer())
4494 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4495 }
4496
Rex Xu1da878f2016-02-21 20:59:01 +08004497 if (symbol->getType().isImage()) {
4498 std::vector<spv::Decoration> memory;
4499 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4500 for (unsigned int i = 0; i < memory.size(); ++i)
4501 addDecoration(id, memory[i]);
4502 }
4503
John Kessenich140f3df2015-06-26 16:58:36 -06004504 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004505 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004506 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004507 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004508
John Kessenich140f3df2015-06-26 16:58:36 -06004509 return id;
4510}
4511
John Kessenich55e7d112015-11-15 21:33:39 -07004512// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004513void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4514{
John Kessenich4016e382016-07-15 11:53:56 -06004515 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004516 builder.addDecoration(id, dec);
4517}
4518
John Kessenich55e7d112015-11-15 21:33:39 -07004519// If 'dec' is valid, add a one-operand decoration to an object
4520void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4521{
John Kessenich4016e382016-07-15 11:53:56 -06004522 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004523 builder.addDecoration(id, dec, value);
4524}
4525
4526// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004527void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4528{
John Kessenich4016e382016-07-15 11:53:56 -06004529 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004530 builder.addMemberDecoration(id, (unsigned)member, dec);
4531}
4532
John Kessenich92187592016-02-01 13:45:25 -07004533// If 'dec' is valid, add a one-operand decoration to a struct member
4534void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4535{
John Kessenich4016e382016-07-15 11:53:56 -06004536 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004537 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4538}
4539
John Kessenich55e7d112015-11-15 21:33:39 -07004540// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004541// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004542//
4543// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4544//
4545// Recursively walk the nodes. The nodes form a tree whose leaves are
4546// regular constants, which themselves are trees that createSpvConstant()
4547// recursively walks. So, this function walks the "top" of the tree:
4548// - emit specialization constant-building instructions for specConstant
4549// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004550spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004551{
John Kessenich7cc0e282016-03-20 00:46:02 -06004552 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004553
qining4f4bb812016-04-03 23:55:17 -04004554 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004555 if (! node.getQualifier().specConstant) {
4556 // hand off to the non-spec-constant path
4557 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4558 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004559 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004560 nextConst, false);
4561 }
4562
4563 // We now know we have a specialization constant to build
4564
John Kessenichd94c0032016-05-30 19:29:40 -06004565 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004566 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4567 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4568 std::vector<spv::Id> dimConstId;
4569 for (int dim = 0; dim < 3; ++dim) {
4570 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4571 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4572 if (specConst)
4573 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4574 }
4575 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4576 }
4577
4578 // An AST node labelled as specialization constant should be a symbol node.
4579 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4580 if (auto* sn = node.getAsSymbolNode()) {
4581 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004582 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4583 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4584 // will set the builder into spec constant op instruction generating mode.
4585 sub_tree->traverse(this);
4586 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004587 } else if (auto* const_union_array = &sn->getConstArray()){
4588 int nextConst = 0;
4589 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004590 }
4591 }
qining4f4bb812016-04-03 23:55:17 -04004592
4593 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4594 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004595 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004596 exit(1);
4597 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004598}
4599
John Kessenich140f3df2015-06-26 16:58:36 -06004600// Use 'consts' as the flattened glslang source of scalar constants to recursively
4601// build the aggregate SPIR-V constant.
4602//
4603// If there are not enough elements present in 'consts', 0 will be substituted;
4604// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4605//
qining08408382016-03-21 09:51:37 -04004606spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004607{
4608 // vector of constants for SPIR-V
4609 std::vector<spv::Id> spvConsts;
4610
4611 // Type is used for struct and array constants
4612 spv::Id typeId = convertGlslangToSpvType(glslangType);
4613
4614 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004615 glslang::TType elementType(glslangType, 0);
4616 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004617 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004618 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004619 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004620 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004621 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004622 } else if (glslangType.getStruct()) {
4623 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4624 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004625 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004626 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004627 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4628 bool zero = nextConst >= consts.size();
4629 switch (glslangType.getBasicType()) {
4630 case glslang::EbtInt:
4631 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4632 break;
4633 case glslang::EbtUint:
4634 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4635 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004636 case glslang::EbtInt64:
4637 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4638 break;
4639 case glslang::EbtUint64:
4640 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4641 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004642 case glslang::EbtFloat:
4643 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4644 break;
4645 case glslang::EbtDouble:
4646 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4647 break;
4648 case glslang::EbtBool:
4649 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4650 break;
4651 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004652 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004653 break;
4654 }
4655 ++nextConst;
4656 }
4657 } else {
4658 // we have a non-aggregate (scalar) constant
4659 bool zero = nextConst >= consts.size();
4660 spv::Id scalar = 0;
4661 switch (glslangType.getBasicType()) {
4662 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004663 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004664 break;
4665 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004666 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004667 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004668 case glslang::EbtInt64:
4669 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4670 break;
4671 case glslang::EbtUint64:
4672 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4673 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004674 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004675 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004676 break;
4677 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004678 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004679 break;
4680 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004681 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004682 break;
4683 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004684 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004685 break;
4686 }
4687 ++nextConst;
4688 return scalar;
4689 }
4690
4691 return builder.makeCompositeConstant(typeId, spvConsts);
4692}
4693
John Kessenich7c1aa102015-10-15 13:29:11 -06004694// Return true if the node is a constant or symbol whose reading has no
4695// non-trivial observable cost or effect.
4696bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4697{
4698 // don't know what this is
4699 if (node == nullptr)
4700 return false;
4701
4702 // a constant is safe
4703 if (node->getAsConstantUnion() != nullptr)
4704 return true;
4705
4706 // not a symbol means non-trivial
4707 if (node->getAsSymbolNode() == nullptr)
4708 return false;
4709
4710 // a symbol, depends on what's being read
4711 switch (node->getType().getQualifier().storage) {
4712 case glslang::EvqTemporary:
4713 case glslang::EvqGlobal:
4714 case glslang::EvqIn:
4715 case glslang::EvqInOut:
4716 case glslang::EvqConst:
4717 case glslang::EvqConstReadOnly:
4718 case glslang::EvqUniform:
4719 return true;
4720 default:
4721 return false;
4722 }
qining25262b32016-05-06 17:25:16 -04004723}
John Kessenich7c1aa102015-10-15 13:29:11 -06004724
4725// A node is trivial if it is a single operation with no side effects.
4726// Error on the side of saying non-trivial.
4727// Return true if trivial.
4728bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4729{
4730 if (node == nullptr)
4731 return false;
4732
4733 // symbols and constants are trivial
4734 if (isTrivialLeaf(node))
4735 return true;
4736
4737 // otherwise, it needs to be a simple operation or one or two leaf nodes
4738
4739 // not a simple operation
4740 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4741 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4742 if (binaryNode == nullptr && unaryNode == nullptr)
4743 return false;
4744
4745 // not on leaf nodes
4746 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4747 return false;
4748
4749 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4750 return false;
4751 }
4752
4753 switch (node->getAsOperator()->getOp()) {
4754 case glslang::EOpLogicalNot:
4755 case glslang::EOpConvIntToBool:
4756 case glslang::EOpConvUintToBool:
4757 case glslang::EOpConvFloatToBool:
4758 case glslang::EOpConvDoubleToBool:
4759 case glslang::EOpEqual:
4760 case glslang::EOpNotEqual:
4761 case glslang::EOpLessThan:
4762 case glslang::EOpGreaterThan:
4763 case glslang::EOpLessThanEqual:
4764 case glslang::EOpGreaterThanEqual:
4765 case glslang::EOpIndexDirect:
4766 case glslang::EOpIndexDirectStruct:
4767 case glslang::EOpLogicalXor:
4768 case glslang::EOpAny:
4769 case glslang::EOpAll:
4770 return true;
4771 default:
4772 return false;
4773 }
4774}
4775
4776// Emit short-circuiting code, where 'right' is never evaluated unless
4777// the left side is true (for &&) or false (for ||).
4778spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4779{
4780 spv::Id boolTypeId = builder.makeBoolType();
4781
4782 // emit left operand
4783 builder.clearAccessChain();
4784 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004785 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004786
4787 // Operands to accumulate OpPhi operands
4788 std::vector<spv::Id> phiOperands;
4789 // accumulate left operand's phi information
4790 phiOperands.push_back(leftId);
4791 phiOperands.push_back(builder.getBuildPoint()->getId());
4792
4793 // Make the two kinds of operation symmetric with a "!"
4794 // || => emit "if (! left) result = right"
4795 // && => emit "if ( left) result = right"
4796 //
4797 // TODO: this runtime "not" for || could be avoided by adding functionality
4798 // to 'builder' to have an "else" without an "then"
4799 if (op == glslang::EOpLogicalOr)
4800 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4801
4802 // make an "if" based on the left value
4803 spv::Builder::If ifBuilder(leftId, builder);
4804
4805 // emit right operand as the "then" part of the "if"
4806 builder.clearAccessChain();
4807 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004808 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004809
4810 // accumulate left operand's phi information
4811 phiOperands.push_back(rightId);
4812 phiOperands.push_back(builder.getBuildPoint()->getId());
4813
4814 // finish the "if"
4815 ifBuilder.makeEndIf();
4816
4817 // phi together the two results
4818 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4819}
4820
Rex Xu9d93a232016-05-05 12:30:44 +08004821// Return type Id of the imported set of extended instructions corresponds to the name.
4822// Import this set if it has not been imported yet.
4823spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
4824{
4825 if (extBuiltinMap.find(name) != extBuiltinMap.end())
4826 return extBuiltinMap[name];
4827 else {
4828 builder.addExtensions(name);
4829 spv::Id extBuiltins = builder.import(name);
4830 extBuiltinMap[name] = extBuiltins;
4831 return extBuiltins;
4832 }
4833}
4834
John Kessenich140f3df2015-06-26 16:58:36 -06004835}; // end anonymous namespace
4836
4837namespace glslang {
4838
John Kessenich68d78fd2015-07-12 19:28:10 -06004839void GetSpirvVersion(std::string& version)
4840{
John Kessenich9e55f632015-07-15 10:03:39 -06004841 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004842 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004843 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004844 version = buf;
4845}
4846
John Kessenich140f3df2015-06-26 16:58:36 -06004847// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004848void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06004849{
4850 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004851 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004852 for (int i = 0; i < (int)spirv.size(); ++i) {
4853 unsigned int word = spirv[i];
4854 out.write((const char*)&word, 4);
4855 }
4856 out.close();
4857}
4858
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004859// Write SPIR-V out to a text file with 32-bit hexadecimal words
4860void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
4861{
4862 std::ofstream out;
4863 out.open(baseName, std::ios::binary | std::ios::out);
4864 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
4865 const int WORDS_PER_LINE = 8;
4866 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
4867 out << "\t";
4868 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
4869 const unsigned int word = spirv[i + j];
4870 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
4871 if (i + j + 1 < (int)spirv.size()) {
4872 out << ",";
4873 }
4874 }
4875 out << std::endl;
4876 }
4877 out.close();
4878}
4879
John Kessenich140f3df2015-06-26 16:58:36 -06004880//
4881// Set up the glslang traversal
4882//
4883void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4884{
Lei Zhang17535f72016-05-04 15:55:59 -04004885 spv::SpvBuildLogger logger;
4886 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004887}
4888
Lei Zhang17535f72016-05-04 15:55:59 -04004889void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004890{
John Kessenich140f3df2015-06-26 16:58:36 -06004891 TIntermNode* root = intermediate.getTreeRoot();
4892
4893 if (root == 0)
4894 return;
4895
4896 glslang::GetThreadPoolAllocator().push();
4897
Lei Zhang17535f72016-05-04 15:55:59 -04004898 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004899
4900 root->traverse(&it);
4901
4902 it.dumpSpv(spirv);
4903
4904 glslang::GetThreadPoolAllocator().pop();
4905}
4906
4907}; // end namespace glslang