blob: 63c3d40ec14c5c15a7456b7858d40e79461c543b [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich6c292d32016-02-15 20:58:50 -07002//Copyright (C) 2014-2015 LunarG, Inc.
3//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//
37// Author: John Kessenich, LunarG
38//
39// Visit the nodes in the glslang intermediate tree representation to
40// translate them to SPIR-V.
41//
42
John Kessenich5e4b1242015-08-06 22:53:06 -060043#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060044#include "GlslangToSpv.h"
45#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060046namespace spv {
47 #include "GLSL.std.450.h"
48}
John Kessenich140f3df2015-06-26 16:58:36 -060049
50// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020051#include "../glslang/MachineIndependent/localintermediate.h"
52#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060054
55#include <string>
56#include <map>
57#include <list>
58#include <vector>
59#include <stack>
60#include <fstream>
61
62namespace {
63
John Kessenich55e7d112015-11-15 21:33:39 -070064// For low-order part of the generator's magic number. Bump up
65// when there is a change in the style (e.g., if SSA form changes,
66// or a different instruction sequence to do something gets used).
67const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060068
qining4c912612016-04-01 10:35:16 -040069namespace {
70class SpecConstantOpModeGuard {
71public:
72 SpecConstantOpModeGuard(spv::Builder* builder)
73 : builder_(builder) {
74 previous_flag_ = builder->isInSpecConstCodeGenMode();
75 builder->setToSpecConstCodeGenMode();
76 }
77 ~SpecConstantOpModeGuard() {
78 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
79 : builder_->setToNormalCodeGenMode();
80 }
81
82private:
83 spv::Builder* builder_;
84 bool previous_flag_;
85};
86}
87
John Kessenich140f3df2015-06-26 16:58:36 -060088//
89// The main holder of information for translating glslang to SPIR-V.
90//
91// Derives from the AST walking base class.
92//
93class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
94public:
95 TGlslangToSpvTraverser(const glslang::TIntermediate*);
96 virtual ~TGlslangToSpvTraverser();
97
98 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
99 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
100 void visitConstantUnion(glslang::TIntermConstantUnion*);
101 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
102 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
103 void visitSymbol(glslang::TIntermSymbol* symbol);
104 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
105 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
106 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
107
John Kessenich7ba63412015-12-20 17:37:07 -0700108 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600109
110protected:
John Kessenich5e801132016-02-15 11:09:46 -0700111 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
John Kessenich92187592016-02-01 13:45:25 -0700112 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable);
John Kessenich5d0fa972016-02-15 11:57:00 -0700113 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600114 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
115 spv::Id getSampledType(const glslang::TSampler&);
116 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700117 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6c292d32016-02-15 20:58:50 -0700118 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700119 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800120 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700121 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700122 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
123 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
124 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich140f3df2015-06-26 16:58:36 -0600125
126 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
127 void makeFunctions(const glslang::TIntermSequence&);
128 void makeGlobalInitializers(const glslang::TIntermSequence&);
129 void visitFunctions(const glslang::TIntermSequence&);
130 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800131 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600132 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
133 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600134 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
135
136 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
John Kessenich04bb8a02015-12-12 12:28:14 -0700137 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800138 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -0700139 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600140 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
141 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800142 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600143 spv::Id 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 -0600144 spv::Id createNoArgOperation(glslang::TOperator op);
145 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
146 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700147 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600148 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700149 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400150 spv::Id createSpvConstant(const glslang::TIntermTyped&);
151 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
qining13545202016-03-21 09:51:37 -0400152 spv::Id createSpvConstantFromConstSubTree(glslang::TIntermTyped* subTree);
John Kessenich7c1aa102015-10-15 13:29:11 -0600153 bool isTrivialLeaf(const glslang::TIntermTyped* node);
154 bool isTrivial(const glslang::TIntermTyped* node);
155 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600156
157 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700158 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600159 int sequenceDepth;
160
161 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
162 spv::Builder builder;
163 bool inMain;
164 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700165 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 -0700166 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600167 const glslang::TIntermediate* glslangIntermediate;
168 spv::Id stdBuiltins;
169
John Kessenich2f273362015-07-18 22:34:27 -0600170 std::unordered_map<int, spv::Id> symbolValues;
171 std::unordered_set<int> constReadOnlyParameters; // set of formal function parameters that have glslang qualifier constReadOnly, so we know they are not local function "const" that are write-once
172 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700173 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600174 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 -0600175 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600176};
177
178//
179// Helper functions for translating glslang representations to SPIR-V enumerants.
180//
181
182// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700183spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600184{
John Kessenich66e2faf2016-03-12 18:34:36 -0700185 switch (source) {
186 case glslang::EShSourceGlsl:
187 switch (profile) {
188 case ENoProfile:
189 case ECoreProfile:
190 case ECompatibilityProfile:
191 return spv::SourceLanguageGLSL;
192 case EEsProfile:
193 return spv::SourceLanguageESSL;
194 default:
195 return spv::SourceLanguageUnknown;
196 }
197 case glslang::EShSourceHlsl:
198 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600199 default:
200 return spv::SourceLanguageUnknown;
201 }
202}
203
204// Translate glslang language (stage) to SPIR-V execution model.
205spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
206{
207 switch (stage) {
208 case EShLangVertex: return spv::ExecutionModelVertex;
209 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
210 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
211 case EShLangGeometry: return spv::ExecutionModelGeometry;
212 case EShLangFragment: return spv::ExecutionModelFragment;
213 case EShLangCompute: return spv::ExecutionModelGLCompute;
214 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700215 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600216 return spv::ExecutionModelFragment;
217 }
218}
219
220// Translate glslang type to SPIR-V storage class.
221spv::StorageClass TranslateStorageClass(const glslang::TType& type)
222{
223 if (type.getQualifier().isPipeInput())
224 return spv::StorageClassInput;
225 else if (type.getQualifier().isPipeOutput())
226 return spv::StorageClassOutput;
227 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700228 if (type.getQualifier().layoutPushConstant)
229 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600230 if (type.getBasicType() == glslang::EbtBlock)
231 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800232 else if (type.getBasicType() == glslang::EbtAtomicUint)
233 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600234 else
235 return spv::StorageClassUniformConstant;
236 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
237 } else {
238 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700239 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
240 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600241 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
242 case glslang::EvqTemporary: return spv::StorageClassFunction;
243 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700244 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600245 return spv::StorageClassFunction;
246 }
247 }
248}
249
250// Translate glslang sampler type to SPIR-V dimensionality.
251spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
252{
253 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700254 case glslang::Esd1D: return spv::Dim1D;
255 case glslang::Esd2D: return spv::Dim2D;
256 case glslang::Esd3D: return spv::Dim3D;
257 case glslang::EsdCube: return spv::DimCube;
258 case glslang::EsdRect: return spv::DimRect;
259 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700260 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600261 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700262 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600263 return spv::Dim2D;
264 }
265}
266
267// Translate glslang type to SPIR-V precision decorations.
268spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
269{
270 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700271 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600272 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600273 default:
274 return spv::NoPrecision;
275 }
276}
277
278// Translate glslang type to SPIR-V block decorations.
279spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
280{
281 if (type.getBasicType() == glslang::EbtBlock) {
282 switch (type.getQualifier().storage) {
283 case glslang::EvqUniform: return spv::DecorationBlock;
284 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
285 case glslang::EvqVaryingIn: return spv::DecorationBlock;
286 case glslang::EvqVaryingOut: return spv::DecorationBlock;
287 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700288 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600289 break;
290 }
291 }
292
293 return (spv::Decoration)spv::BadValue;
294}
295
Rex Xu1da878f2016-02-21 20:59:01 +0800296// Translate glslang type to SPIR-V memory decorations.
297void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
298{
299 if (qualifier.coherent)
300 memory.push_back(spv::DecorationCoherent);
301 if (qualifier.volatil)
302 memory.push_back(spv::DecorationVolatile);
303 if (qualifier.restrict)
304 memory.push_back(spv::DecorationRestrict);
305 if (qualifier.readonly)
306 memory.push_back(spv::DecorationNonWritable);
307 if (qualifier.writeonly)
308 memory.push_back(spv::DecorationNonReadable);
309}
310
John Kessenich140f3df2015-06-26 16:58:36 -0600311// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700312spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600313{
314 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700315 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600316 case glslang::ElmRowMajor:
317 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700318 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600319 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700320 default:
321 // opaque layouts don't need a majorness
322 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600323 }
324 } else {
325 switch (type.getBasicType()) {
326 default:
327 return (spv::Decoration)spv::BadValue;
328 break;
329 case glslang::EbtBlock:
330 switch (type.getQualifier().storage) {
331 case glslang::EvqUniform:
332 case glslang::EvqBuffer:
333 switch (type.getQualifier().layoutPacking) {
334 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600335 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
336 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600337 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600338 }
339 case glslang::EvqVaryingIn:
340 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700341 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600342 return (spv::Decoration)spv::BadValue;
343 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700344 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600345 return (spv::Decoration)spv::BadValue;
346 }
347 }
348 }
349}
350
351// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700352// Returns spv::Decoration(spv::BadValue) when no decoration
353// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700354spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600355{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700356 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700357 // Smooth decoration doesn't exist in SPIR-V 1.0
358 return (spv::Decoration)spv::BadValue;
359 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700360 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700361 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700362 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600363 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700364 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600365 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700366 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600367 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700368 else if (qualifier.sample) {
369 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600370 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700371 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600372 return (spv::Decoration)spv::BadValue;
373}
374
John Kessenich92187592016-02-01 13:45:25 -0700375// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700376spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600377{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700378 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600379 return spv::DecorationInvariant;
380 else
381 return (spv::Decoration)spv::BadValue;
382}
383
384// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700385spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600386{
387 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700388 case glslang::EbvPointSize:
389 switch (glslangIntermediate->getStage()) {
390 case EShLangGeometry:
391 builder.addCapability(spv::CapabilityGeometryPointSize);
392 break;
393 case EShLangTessControl:
394 case EShLangTessEvaluation:
395 builder.addCapability(spv::CapabilityTessellationPointSize);
396 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100397 default:
398 break;
John Kessenich92187592016-02-01 13:45:25 -0700399 }
400 return spv::BuiltInPointSize;
401
402 case glslang::EbvClipDistance:
403 builder.addCapability(spv::CapabilityClipDistance);
404 return spv::BuiltInClipDistance;
405
406 case glslang::EbvCullDistance:
407 builder.addCapability(spv::CapabilityCullDistance);
408 return spv::BuiltInCullDistance;
409
410 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500411 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700412 return spv::BuiltInViewportIndex;
413
John Kessenich5e801132016-02-15 11:09:46 -0700414 case glslang::EbvSampleId:
415 builder.addCapability(spv::CapabilitySampleRateShading);
416 return spv::BuiltInSampleId;
417
418 case glslang::EbvSamplePosition:
419 builder.addCapability(spv::CapabilitySampleRateShading);
420 return spv::BuiltInSamplePosition;
421
422 case glslang::EbvSampleMask:
423 builder.addCapability(spv::CapabilitySampleRateShading);
424 return spv::BuiltInSampleMask;
425
John Kessenich140f3df2015-06-26 16:58:36 -0600426 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600427 case glslang::EbvVertexId: return spv::BuiltInVertexId;
428 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700429 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
430 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600431 case glslang::EbvBaseVertex:
432 case glslang::EbvBaseInstance:
433 case glslang::EbvDrawId:
434 // TODO: Add SPIR-V builtin ID.
435 spv::MissingFunctionality("Draw parameters");
436 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600437 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
438 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
439 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600440 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
441 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
442 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
443 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
444 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
445 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
446 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600447 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
448 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
449 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
450 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
451 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
452 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
453 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
454 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
455 default: return (spv::BuiltIn)spv::BadValue;
456 }
457}
458
Rex Xufc618912015-09-09 16:42:49 +0800459// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700460spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800461{
462 assert(type.getBasicType() == glslang::EbtSampler);
463
John Kessenich5d0fa972016-02-15 11:57:00 -0700464 // Check for capabilities
465 switch (type.getQualifier().layoutFormat) {
466 case glslang::ElfRg32f:
467 case glslang::ElfRg16f:
468 case glslang::ElfR11fG11fB10f:
469 case glslang::ElfR16f:
470 case glslang::ElfRgba16:
471 case glslang::ElfRgb10A2:
472 case glslang::ElfRg16:
473 case glslang::ElfRg8:
474 case glslang::ElfR16:
475 case glslang::ElfR8:
476 case glslang::ElfRgba16Snorm:
477 case glslang::ElfRg16Snorm:
478 case glslang::ElfRg8Snorm:
479 case glslang::ElfR16Snorm:
480 case glslang::ElfR8Snorm:
481
482 case glslang::ElfRg32i:
483 case glslang::ElfRg16i:
484 case glslang::ElfRg8i:
485 case glslang::ElfR16i:
486 case glslang::ElfR8i:
487
488 case glslang::ElfRgb10a2ui:
489 case glslang::ElfRg32ui:
490 case glslang::ElfRg16ui:
491 case glslang::ElfRg8ui:
492 case glslang::ElfR16ui:
493 case glslang::ElfR8ui:
494 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
495 break;
496
497 default:
498 break;
499 }
500
501 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800502 switch (type.getQualifier().layoutFormat) {
503 case glslang::ElfNone: return spv::ImageFormatUnknown;
504 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
505 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
506 case glslang::ElfR32f: return spv::ImageFormatR32f;
507 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
508 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
509 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
510 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
511 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
512 case glslang::ElfR16f: return spv::ImageFormatR16f;
513 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
514 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
515 case glslang::ElfRg16: return spv::ImageFormatRg16;
516 case glslang::ElfRg8: return spv::ImageFormatRg8;
517 case glslang::ElfR16: return spv::ImageFormatR16;
518 case glslang::ElfR8: return spv::ImageFormatR8;
519 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
520 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
521 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
522 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
523 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
524 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
525 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
526 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
527 case glslang::ElfR32i: return spv::ImageFormatR32i;
528 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
529 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
530 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
531 case glslang::ElfR16i: return spv::ImageFormatR16i;
532 case glslang::ElfR8i: return spv::ImageFormatR8i;
533 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
534 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
535 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
536 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
537 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
538 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
539 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
540 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
541 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
542 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
543 default: return (spv::ImageFormat)spv::BadValue;
544 }
545}
546
John Kessenich6c292d32016-02-15 20:58:50 -0700547// Return whether or not the given type is something that should be tied to a
548// descriptor set.
549bool IsDescriptorResource(const glslang::TType& type)
550{
John Kessenichf7497e22016-03-08 21:36:22 -0700551 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700552 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700553 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700554
555 // non block...
556 // basically samplerXXX/subpass/sampler/texture are all included
557 // if they are the global-scope-class, not the function parameter
558 // (or local, if they ever exist) class.
559 if (type.getBasicType() == glslang::EbtSampler)
560 return type.getQualifier().isUniformOrBuffer();
561
562 // None of the above.
563 return false;
564}
565
John Kesseniche0b6cad2015-12-24 10:30:13 -0700566void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
567{
568 if (child.layoutMatrix == glslang::ElmNone)
569 child.layoutMatrix = parent.layoutMatrix;
570
571 if (parent.invariant)
572 child.invariant = true;
573 if (parent.nopersp)
574 child.nopersp = true;
575 if (parent.flat)
576 child.flat = true;
577 if (parent.centroid)
578 child.centroid = true;
579 if (parent.patch)
580 child.patch = true;
581 if (parent.sample)
582 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800583 if (parent.coherent)
584 child.coherent = true;
585 if (parent.volatil)
586 child.volatil = true;
587 if (parent.restrict)
588 child.restrict = true;
589 if (parent.readonly)
590 child.readonly = true;
591 if (parent.writeonly)
592 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700593}
594
595bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
596{
John Kessenich7b9fa252016-01-21 18:56:57 -0700597 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700598 // - struct members can inherit from a struct declaration
599 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
600 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700601 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700602}
603
John Kessenich140f3df2015-06-26 16:58:36 -0600604//
605// Implement the TGlslangToSpvTraverser class.
606//
607
608TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
609 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700610 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600611 inMain(false), mainTerminated(false), linkageOnly(false),
612 glslangIntermediate(glslangIntermediate)
613{
614 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
615
616 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700617 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600618 stdBuiltins = builder.import("GLSL.std.450");
619 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700620 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
621 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600622
623 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600624 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
625 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600626 builder.addSourceExtension(it->c_str());
627
628 // Add the top-level modes for this shader.
629
John Kessenich92187592016-02-01 13:45:25 -0700630 if (glslangIntermediate->getXfbMode()) {
631 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600632 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700633 }
John Kessenich140f3df2015-06-26 16:58:36 -0600634
635 unsigned int mode;
636 switch (glslangIntermediate->getStage()) {
637 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600638 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600639 break;
640
641 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600642 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600643 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
644 break;
645
646 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600647 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600648 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700649 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
650 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
651 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600652 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600653 }
654 if (mode != spv::BadValue)
655 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
656
John Kesseniche6903322015-10-13 16:29:02 -0600657 switch (glslangIntermediate->getVertexSpacing()) {
658 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
659 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
660 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
661 default: mode = spv::BadValue; break;
662 }
663 if (mode != spv::BadValue)
664 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
665
666 switch (glslangIntermediate->getVertexOrder()) {
667 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
668 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
669 default: mode = spv::BadValue; break;
670 }
671 if (mode != spv::BadValue)
672 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
673
674 if (glslangIntermediate->getPointMode())
675 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600676 break;
677
678 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600679 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600680 switch (glslangIntermediate->getInputPrimitive()) {
681 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
682 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
683 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700684 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600685 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
686 default: mode = spv::BadValue; break;
687 }
688 if (mode != spv::BadValue)
689 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600690
John Kessenich140f3df2015-06-26 16:58:36 -0600691 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
692
693 switch (glslangIntermediate->getOutputPrimitive()) {
694 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
695 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
696 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
697 default: mode = spv::BadValue; break;
698 }
699 if (mode != spv::BadValue)
700 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
701 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
702 break;
703
704 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600705 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600706 if (glslangIntermediate->getPixelCenterInteger())
707 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600708
John Kessenich140f3df2015-06-26 16:58:36 -0600709 if (glslangIntermediate->getOriginUpperLeft())
710 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600711 else
712 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600713
714 if (glslangIntermediate->getEarlyFragmentTests())
715 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
716
717 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600718 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
719 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
720 default: mode = spv::BadValue; break;
721 }
722 if (mode != spv::BadValue)
723 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
724
725 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
726 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600727 break;
728
729 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600730 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600731 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
732 glslangIntermediate->getLocalSize(1),
733 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600734 break;
735
736 default:
737 break;
738 }
739
740}
741
John Kessenich7ba63412015-12-20 17:37:07 -0700742// Finish everything and dump
743void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
744{
745 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100746 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
747 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700748
qiningda397332016-03-09 19:54:03 -0500749 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700750 builder.dump(out);
751}
752
John Kessenich140f3df2015-06-26 16:58:36 -0600753TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
754{
755 if (! mainTerminated) {
756 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
757 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600758 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600759 }
760}
761
762//
763// Implement the traversal functions.
764//
765// Return true from interior nodes to have the external traversal
766// continue on to children. Return false if children were
767// already processed.
768//
769
770//
771// Symbols can turn into
772// - uniform/input reads
773// - output writes
774// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
775// - something simple that degenerates into the last bullet
776//
777void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
778{
779 // getSymbolId() will set up all the IO decorations on the first call.
780 // Formal function parameters were mapped during makeFunctions().
781 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700782
783 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
784 if (builder.isPointer(id)) {
785 spv::StorageClass sc = builder.getStorageClass(id);
786 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
787 iOSet.insert(id);
788 }
789
790 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700791 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600792 // Prepare to generate code for the access
793
794 // L-value chains will be computed left to right. We're on the symbol now,
795 // which is the left-most part of the access chain, so now is "clear" time,
796 // followed by setting the base.
797 builder.clearAccessChain();
798
799 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700800 // except for
801 // A) "const in" arguments to a function, which are an intermediate object.
802 // See comments in handleUserFunctionCall().
803 // B) Specialization constants (normal constant don't even come in as a variable),
804 // These are also pure R-values.
805 glslang::TQualifier qualifier = symbol->getQualifier();
806 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
807 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600808 builder.setAccessChainRValue(id);
809 else
810 builder.setAccessChainLValue(id);
811 }
812}
813
814bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
815{
816 // First, handle special cases
817 switch (node->getOp()) {
818 case glslang::EOpAssign:
819 case glslang::EOpAddAssign:
820 case glslang::EOpSubAssign:
821 case glslang::EOpMulAssign:
822 case glslang::EOpVectorTimesMatrixAssign:
823 case glslang::EOpVectorTimesScalarAssign:
824 case glslang::EOpMatrixTimesScalarAssign:
825 case glslang::EOpMatrixTimesMatrixAssign:
826 case glslang::EOpDivAssign:
827 case glslang::EOpModAssign:
828 case glslang::EOpAndAssign:
829 case glslang::EOpInclusiveOrAssign:
830 case glslang::EOpExclusiveOrAssign:
831 case glslang::EOpLeftShiftAssign:
832 case glslang::EOpRightShiftAssign:
833 // A bin-op assign "a += b" means the same thing as "a = a + b"
834 // where a is evaluated before b. For a simple assignment, GLSL
835 // says to evaluate the left before the right. So, always, left
836 // node then right node.
837 {
838 // get the left l-value, save it away
839 builder.clearAccessChain();
840 node->getLeft()->traverse(this);
841 spv::Builder::AccessChain lValue = builder.getAccessChain();
842
843 // evaluate the right
844 builder.clearAccessChain();
845 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700846 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600847
848 if (node->getOp() != glslang::EOpAssign) {
849 // the left is also an r-value
850 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700851 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600852
853 // do the operation
854 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
855 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
856 node->getType().getBasicType());
857
858 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700859 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600860 }
861
862 // store the result
863 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800864 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600865
866 // assignments are expressions having an rValue after they are evaluated...
867 builder.clearAccessChain();
868 builder.setAccessChainRValue(rValue);
869 }
870 return false;
871 case glslang::EOpIndexDirect:
872 case glslang::EOpIndexDirectStruct:
873 {
874 // Get the left part of the access chain.
875 node->getLeft()->traverse(this);
876
877 // Add the next element in the chain
878
John Kessenich55e7d112015-11-15 21:33:39 -0700879 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600880 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
881 // This may be, e.g., an anonymous block-member selection, which generally need
882 // index remapping due to hidden members in anonymous blocks.
883 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700884 assert(remapper.size() > 0);
885 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600886 }
887
888 if (! node->getLeft()->getType().isArray() &&
889 node->getLeft()->getType().isVector() &&
890 node->getOp() == glslang::EOpIndexDirect) {
891 // This is essentially a hard-coded vector swizzle of size 1,
892 // so short circuit the access-chain stuff with a swizzle.
893 std::vector<unsigned> swizzle;
894 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600895 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600896 } else {
897 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600898 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600899 }
900 }
901 return false;
902 case glslang::EOpIndexIndirect:
903 {
904 // Structure or array or vector indirection.
905 // Will use native SPIR-V access-chain for struct and array indirection;
906 // matrices are arrays of vectors, so will also work for a matrix.
907 // Will use the access chain's 'component' for variable index into a vector.
908
909 // This adapter is building access chains left to right.
910 // Set up the access chain to the left.
911 node->getLeft()->traverse(this);
912
913 // save it so that computing the right side doesn't trash it
914 spv::Builder::AccessChain partial = builder.getAccessChain();
915
916 // compute the next index in the chain
917 builder.clearAccessChain();
918 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700919 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600920
921 // restore the saved access chain
922 builder.setAccessChain(partial);
923
924 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600925 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600926 else
John Kessenichfa668da2015-09-13 14:46:30 -0600927 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600928 }
929 return false;
930 case glslang::EOpVectorSwizzle:
931 {
932 node->getLeft()->traverse(this);
933 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
934 std::vector<unsigned> swizzle;
935 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
936 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600937 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600938 }
939 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600940 case glslang::EOpLogicalOr:
941 case glslang::EOpLogicalAnd:
942 {
943
944 // These may require short circuiting, but can sometimes be done as straight
945 // binary operations. The right operand must be short circuited if it has
946 // side effects, and should probably be if it is complex.
947 if (isTrivial(node->getRight()->getAsTyped()))
948 break; // handle below as a normal binary operation
949 // otherwise, we need to do dynamic short circuiting on the right operand
950 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
951 builder.clearAccessChain();
952 builder.setAccessChainRValue(result);
953 }
954 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600955 default:
956 break;
957 }
958
959 // Assume generic binary op...
960
John Kessenich32cfd492016-02-02 12:37:46 -0700961 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600962 builder.clearAccessChain();
963 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700964 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600965
John Kessenich32cfd492016-02-02 12:37:46 -0700966 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600967 builder.clearAccessChain();
968 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700969 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600970
John Kessenich32cfd492016-02-02 12:37:46 -0700971 // get result
972 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
973 convertGlslangToSpvType(node->getType()), left, right,
974 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600975
John Kessenich50e57562015-12-21 21:21:11 -0700976 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600977 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700978 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700979 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600980 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600981 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600982 return false;
983 }
John Kessenich140f3df2015-06-26 16:58:36 -0600984}
985
986bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
987{
John Kessenichfc51d282015-08-19 13:34:18 -0600988 spv::Id result = spv::NoResult;
989
990 // try texturing first
991 result = createImageTextureFunctionCall(node);
992 if (result != spv::NoResult) {
993 builder.clearAccessChain();
994 builder.setAccessChainRValue(result);
995
996 return false; // done with this node
997 }
998
999 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001000
1001 if (node->getOp() == glslang::EOpArrayLength) {
1002 // Quite special; won't want to evaluate the operand.
1003
1004 // Normal .length() would have been constant folded by the front-end.
1005 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001006 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001007 assert(node->getOperand()->getType().isRuntimeSizedArray());
1008 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1009 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001010 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1011 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001012
1013 builder.clearAccessChain();
1014 builder.setAccessChainRValue(length);
1015
1016 return false;
1017 }
1018
John Kessenichfc51d282015-08-19 13:34:18 -06001019 // Start by evaluating the operand
1020
John Kessenich140f3df2015-06-26 16:58:36 -06001021 builder.clearAccessChain();
1022 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001023
Rex Xufc618912015-09-09 16:42:49 +08001024 spv::Id operand = spv::NoResult;
1025
1026 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1027 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001028 node->getOp() == glslang::EOpAtomicCounter ||
1029 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001030 operand = builder.accessChainGetLValue(); // Special case l-value operands
1031 else
John Kessenich32cfd492016-02-02 12:37:46 -07001032 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001033
1034 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1035
1036 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001037 if (! result)
1038 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -06001039
1040 // if not, then possibly an operation
1041 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -07001042 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001043
1044 if (result) {
1045 builder.clearAccessChain();
1046 builder.setAccessChainRValue(result);
1047
1048 return false; // done with this node
1049 }
1050
1051 // it must be a special case, check...
1052 switch (node->getOp()) {
1053 case glslang::EOpPostIncrement:
1054 case glslang::EOpPostDecrement:
1055 case glslang::EOpPreIncrement:
1056 case glslang::EOpPreDecrement:
1057 {
1058 // we need the integer value "1" or the floating point "1.0" to add/subtract
1059 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
1060 builder.makeFloatConstant(1.0F) :
1061 builder.makeIntConstant(1);
1062 glslang::TOperator op;
1063 if (node->getOp() == glslang::EOpPreIncrement ||
1064 node->getOp() == glslang::EOpPostIncrement)
1065 op = glslang::EOpAdd;
1066 else
1067 op = glslang::EOpSub;
1068
1069 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1070 convertGlslangToSpvType(node->getType()), operand, one,
1071 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001072 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001073
1074 // The result of operation is always stored, but conditionally the
1075 // consumed result. The consumed result is always an r-value.
1076 builder.accessChainStore(result);
1077 builder.clearAccessChain();
1078 if (node->getOp() == glslang::EOpPreIncrement ||
1079 node->getOp() == glslang::EOpPreDecrement)
1080 builder.setAccessChainRValue(result);
1081 else
1082 builder.setAccessChainRValue(operand);
1083 }
1084
1085 return false;
1086
1087 case glslang::EOpEmitStreamVertex:
1088 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1089 return false;
1090 case glslang::EOpEndStreamPrimitive:
1091 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1092 return false;
1093
1094 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001095 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001096 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001097 }
John Kessenich140f3df2015-06-26 16:58:36 -06001098}
1099
1100bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1101{
John Kessenichfc51d282015-08-19 13:34:18 -06001102 spv::Id result = spv::NoResult;
1103
1104 // try texturing
1105 result = createImageTextureFunctionCall(node);
1106 if (result != spv::NoResult) {
1107 builder.clearAccessChain();
1108 builder.setAccessChainRValue(result);
1109
1110 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001111 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001112 // "imageStore" is a special case, which has no result
1113 return false;
1114 }
John Kessenichfc51d282015-08-19 13:34:18 -06001115
John Kessenich140f3df2015-06-26 16:58:36 -06001116 glslang::TOperator binOp = glslang::EOpNull;
1117 bool reduceComparison = true;
1118 bool isMatrix = false;
1119 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001120 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001121
1122 assert(node->getOp());
1123
1124 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1125
1126 switch (node->getOp()) {
1127 case glslang::EOpSequence:
1128 {
1129 if (preVisit)
1130 ++sequenceDepth;
1131 else
1132 --sequenceDepth;
1133
1134 if (sequenceDepth == 1) {
1135 // If this is the parent node of all the functions, we want to see them
1136 // early, so all call points have actual SPIR-V functions to reference.
1137 // In all cases, still let the traverser visit the children for us.
1138 makeFunctions(node->getAsAggregate()->getSequence());
1139
1140 // Also, we want all globals initializers to go into the entry of main(), before
1141 // anything else gets there, so visit out of order, doing them all now.
1142 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1143
1144 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1145 // so do them manually.
1146 visitFunctions(node->getAsAggregate()->getSequence());
1147
1148 return false;
1149 }
1150
1151 return true;
1152 }
1153 case glslang::EOpLinkerObjects:
1154 {
1155 if (visit == glslang::EvPreVisit)
1156 linkageOnly = true;
1157 else
1158 linkageOnly = false;
1159
1160 return true;
1161 }
1162 case glslang::EOpComma:
1163 {
1164 // processing from left to right naturally leaves the right-most
1165 // lying around in the access chain
1166 glslang::TIntermSequence& glslangOperands = node->getSequence();
1167 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1168 glslangOperands[i]->traverse(this);
1169
1170 return false;
1171 }
1172 case glslang::EOpFunction:
1173 if (visit == glslang::EvPreVisit) {
1174 if (isShaderEntrypoint(node)) {
1175 inMain = true;
1176 builder.setBuildPoint(shaderEntry->getLastBlock());
1177 } else {
1178 handleFunctionEntry(node);
1179 }
1180 } else {
1181 if (inMain)
1182 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001183 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001184 inMain = false;
1185 }
1186
1187 return true;
1188 case glslang::EOpParameters:
1189 // Parameters will have been consumed by EOpFunction processing, but not
1190 // the body, so we still visited the function node's children, making this
1191 // child redundant.
1192 return false;
1193 case glslang::EOpFunctionCall:
1194 {
1195 if (node->isUserDefined())
1196 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001197 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1198 if (result) {
1199 builder.clearAccessChain();
1200 builder.setAccessChainRValue(result);
1201 } else
1202 spv::MissingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001203
1204 return false;
1205 }
1206 case glslang::EOpConstructMat2x2:
1207 case glslang::EOpConstructMat2x3:
1208 case glslang::EOpConstructMat2x4:
1209 case glslang::EOpConstructMat3x2:
1210 case glslang::EOpConstructMat3x3:
1211 case glslang::EOpConstructMat3x4:
1212 case glslang::EOpConstructMat4x2:
1213 case glslang::EOpConstructMat4x3:
1214 case glslang::EOpConstructMat4x4:
1215 case glslang::EOpConstructDMat2x2:
1216 case glslang::EOpConstructDMat2x3:
1217 case glslang::EOpConstructDMat2x4:
1218 case glslang::EOpConstructDMat3x2:
1219 case glslang::EOpConstructDMat3x3:
1220 case glslang::EOpConstructDMat3x4:
1221 case glslang::EOpConstructDMat4x2:
1222 case glslang::EOpConstructDMat4x3:
1223 case glslang::EOpConstructDMat4x4:
1224 isMatrix = true;
1225 // fall through
1226 case glslang::EOpConstructFloat:
1227 case glslang::EOpConstructVec2:
1228 case glslang::EOpConstructVec3:
1229 case glslang::EOpConstructVec4:
1230 case glslang::EOpConstructDouble:
1231 case glslang::EOpConstructDVec2:
1232 case glslang::EOpConstructDVec3:
1233 case glslang::EOpConstructDVec4:
1234 case glslang::EOpConstructBool:
1235 case glslang::EOpConstructBVec2:
1236 case glslang::EOpConstructBVec3:
1237 case glslang::EOpConstructBVec4:
1238 case glslang::EOpConstructInt:
1239 case glslang::EOpConstructIVec2:
1240 case glslang::EOpConstructIVec3:
1241 case glslang::EOpConstructIVec4:
1242 case glslang::EOpConstructUint:
1243 case glslang::EOpConstructUVec2:
1244 case glslang::EOpConstructUVec3:
1245 case glslang::EOpConstructUVec4:
1246 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001247 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001248 {
1249 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001250 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001251 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1252 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001253 if (node->getOp() == glslang::EOpConstructTextureSampler)
1254 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1255 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001256 std::vector<spv::Id> constituents;
1257 for (int c = 0; c < (int)arguments.size(); ++c)
1258 constituents.push_back(arguments[c]);
1259 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001260 } else if (isMatrix)
1261 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1262 else
1263 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001264
1265 builder.clearAccessChain();
1266 builder.setAccessChainRValue(constructed);
1267
1268 return false;
1269 }
1270
1271 // These six are component-wise compares with component-wise results.
1272 // Forward on to createBinaryOperation(), requesting a vector result.
1273 case glslang::EOpLessThan:
1274 case glslang::EOpGreaterThan:
1275 case glslang::EOpLessThanEqual:
1276 case glslang::EOpGreaterThanEqual:
1277 case glslang::EOpVectorEqual:
1278 case glslang::EOpVectorNotEqual:
1279 {
1280 // Map the operation to a binary
1281 binOp = node->getOp();
1282 reduceComparison = false;
1283 switch (node->getOp()) {
1284 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1285 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1286 default: binOp = node->getOp(); break;
1287 }
1288
1289 break;
1290 }
1291 case glslang::EOpMul:
1292 // compontent-wise matrix multiply
1293 binOp = glslang::EOpMul;
1294 break;
1295 case glslang::EOpOuterProduct:
1296 // two vectors multiplied to make a matrix
1297 binOp = glslang::EOpOuterProduct;
1298 break;
1299 case glslang::EOpDot:
1300 {
1301 // for scalar dot product, use multiply
1302 glslang::TIntermSequence& glslangOperands = node->getSequence();
1303 if (! glslangOperands[0]->getAsTyped()->isVector())
1304 binOp = glslang::EOpMul;
1305 break;
1306 }
1307 case glslang::EOpMod:
1308 // when an aggregate, this is the floating-point mod built-in function,
1309 // which can be emitted by the one in createBinaryOperation()
1310 binOp = glslang::EOpMod;
1311 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001312 case glslang::EOpEmitVertex:
1313 case glslang::EOpEndPrimitive:
1314 case glslang::EOpBarrier:
1315 case glslang::EOpMemoryBarrier:
1316 case glslang::EOpMemoryBarrierAtomicCounter:
1317 case glslang::EOpMemoryBarrierBuffer:
1318 case glslang::EOpMemoryBarrierImage:
1319 case glslang::EOpMemoryBarrierShared:
1320 case glslang::EOpGroupMemoryBarrier:
1321 noReturnValue = true;
1322 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1323 break;
1324
John Kessenich426394d2015-07-23 10:22:48 -06001325 case glslang::EOpAtomicAdd:
1326 case glslang::EOpAtomicMin:
1327 case glslang::EOpAtomicMax:
1328 case glslang::EOpAtomicAnd:
1329 case glslang::EOpAtomicOr:
1330 case glslang::EOpAtomicXor:
1331 case glslang::EOpAtomicExchange:
1332 case glslang::EOpAtomicCompSwap:
1333 atomic = true;
1334 break;
1335
John Kessenich140f3df2015-06-26 16:58:36 -06001336 default:
1337 break;
1338 }
1339
1340 //
1341 // See if it maps to a regular operation.
1342 //
John Kessenich140f3df2015-06-26 16:58:36 -06001343 if (binOp != glslang::EOpNull) {
1344 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1345 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1346 assert(left && right);
1347
1348 builder.clearAccessChain();
1349 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001350 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001351
1352 builder.clearAccessChain();
1353 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001354 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001355
1356 result = createBinaryOperation(binOp, precision,
1357 convertGlslangToSpvType(node->getType()), leftId, rightId,
1358 left->getType().getBasicType(), reduceComparison);
1359
1360 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001361 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001362 builder.clearAccessChain();
1363 builder.setAccessChainRValue(result);
1364
1365 return false;
1366 }
1367
John Kessenich426394d2015-07-23 10:22:48 -06001368 //
1369 // Create the list of operands.
1370 //
John Kessenich140f3df2015-06-26 16:58:36 -06001371 glslang::TIntermSequence& glslangOperands = node->getSequence();
1372 std::vector<spv::Id> operands;
1373 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1374 builder.clearAccessChain();
1375 glslangOperands[arg]->traverse(this);
1376
1377 // special case l-value operands; there are just a few
1378 bool lvalue = false;
1379 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001380 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001381 case glslang::EOpModf:
1382 if (arg == 1)
1383 lvalue = true;
1384 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001385 case glslang::EOpInterpolateAtSample:
1386 case glslang::EOpInterpolateAtOffset:
1387 if (arg == 0)
1388 lvalue = true;
1389 break;
Rex Xud4782c12015-09-06 16:30:11 +08001390 case glslang::EOpAtomicAdd:
1391 case glslang::EOpAtomicMin:
1392 case glslang::EOpAtomicMax:
1393 case glslang::EOpAtomicAnd:
1394 case glslang::EOpAtomicOr:
1395 case glslang::EOpAtomicXor:
1396 case glslang::EOpAtomicExchange:
1397 case glslang::EOpAtomicCompSwap:
1398 if (arg == 0)
1399 lvalue = true;
1400 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001401 case glslang::EOpAddCarry:
1402 case glslang::EOpSubBorrow:
1403 if (arg == 2)
1404 lvalue = true;
1405 break;
1406 case glslang::EOpUMulExtended:
1407 case glslang::EOpIMulExtended:
1408 if (arg >= 2)
1409 lvalue = true;
1410 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001411 default:
1412 break;
1413 }
1414 if (lvalue)
1415 operands.push_back(builder.accessChainGetLValue());
1416 else
John Kessenich32cfd492016-02-02 12:37:46 -07001417 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001418 }
John Kessenich426394d2015-07-23 10:22:48 -06001419
1420 if (atomic) {
1421 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001422 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001423 } else {
1424 // Pass through to generic operations.
1425 switch (glslangOperands.size()) {
1426 case 0:
1427 result = createNoArgOperation(node->getOp());
1428 break;
1429 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001430 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001431 break;
1432 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001433 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001434 break;
1435 }
John Kessenich140f3df2015-06-26 16:58:36 -06001436 }
1437
1438 if (noReturnValue)
1439 return false;
1440
1441 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001442 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001443 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001444 } else {
1445 builder.clearAccessChain();
1446 builder.setAccessChainRValue(result);
1447 return false;
1448 }
1449}
1450
1451bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1452{
1453 // This path handles both if-then-else and ?:
1454 // The if-then-else has a node type of void, while
1455 // ?: has a non-void node type
1456 spv::Id result = 0;
1457 if (node->getBasicType() != glslang::EbtVoid) {
1458 // don't handle this as just on-the-fly temporaries, because there will be two names
1459 // and better to leave SSA to later passes
1460 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1461 }
1462
1463 // emit the condition before doing anything with selection
1464 node->getCondition()->traverse(this);
1465
1466 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001467 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001468
1469 if (node->getTrueBlock()) {
1470 // emit the "then" statement
1471 node->getTrueBlock()->traverse(this);
1472 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001473 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001474 }
1475
1476 if (node->getFalseBlock()) {
1477 ifBuilder.makeBeginElse();
1478 // emit the "else" statement
1479 node->getFalseBlock()->traverse(this);
1480 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001481 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001482 }
1483
1484 ifBuilder.makeEndIf();
1485
1486 if (result) {
1487 // GLSL only has r-values as the result of a :?, but
1488 // if we have an l-value, that can be more efficient if it will
1489 // become the base of a complex r-value expression, because the
1490 // next layer copies r-values into memory to use the access-chain mechanism
1491 builder.clearAccessChain();
1492 builder.setAccessChainLValue(result);
1493 }
1494
1495 return false;
1496}
1497
1498bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1499{
1500 // emit and get the condition before doing anything with switch
1501 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001502 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001503
1504 // browse the children to sort out code segments
1505 int defaultSegment = -1;
1506 std::vector<TIntermNode*> codeSegments;
1507 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1508 std::vector<int> caseValues;
1509 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1510 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1511 TIntermNode* child = *c;
1512 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001513 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001514 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001515 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001516 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1517 } else
1518 codeSegments.push_back(child);
1519 }
1520
1521 // handle the case where the last code segment is missing, due to no code
1522 // statements between the last case and the end of the switch statement
1523 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1524 (int)codeSegments.size() == defaultSegment)
1525 codeSegments.push_back(nullptr);
1526
1527 // make the switch statement
1528 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001529 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001530
1531 // emit all the code in the segments
1532 breakForLoop.push(false);
1533 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1534 builder.nextSwitchSegment(segmentBlocks, s);
1535 if (codeSegments[s])
1536 codeSegments[s]->traverse(this);
1537 else
1538 builder.addSwitchBreak();
1539 }
1540 breakForLoop.pop();
1541
1542 builder.endSwitch(segmentBlocks);
1543
1544 return false;
1545}
1546
1547void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1548{
1549 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001550 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001551
1552 builder.clearAccessChain();
1553 builder.setAccessChainRValue(constant);
1554}
1555
1556bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1557{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001558 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001559 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001560 // Spec requires back edges to target header blocks, and every header block
1561 // must dominate its merge block. Make a header block first to ensure these
1562 // conditions are met. By definition, it will contain OpLoopMerge, followed
1563 // by a block-ending branch. But we don't want to put any other body/test
1564 // instructions in it, since the body/test may have arbitrary instructions,
1565 // including merges of its own.
1566 builder.setBuildPoint(&blocks.head);
1567 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001568 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001569 spv::Block& test = builder.makeNewBlock();
1570 builder.createBranch(&test);
1571
1572 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001573 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001574 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001575 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001576 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1577
1578 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001579 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001580 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001581 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001582 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001583 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001584
1585 builder.setBuildPoint(&blocks.continue_target);
1586 if (node->getTerminal())
1587 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001588 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001589 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001590 builder.createBranch(&blocks.body);
1591
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001592 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001593 builder.setBuildPoint(&blocks.body);
1594 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001595 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001596 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001597 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001598
1599 builder.setBuildPoint(&blocks.continue_target);
1600 if (node->getTerminal())
1601 node->getTerminal()->traverse(this);
1602 if (node->getTest()) {
1603 node->getTest()->traverse(this);
1604 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001605 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001606 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001607 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001608 // TODO: unless there was a break/return/discard instruction
1609 // somewhere in the body, this is an infinite loop, so we should
1610 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001611 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001612 }
John Kessenich140f3df2015-06-26 16:58:36 -06001613 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001614 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001615 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001616 return false;
1617}
1618
1619bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1620{
1621 if (node->getExpression())
1622 node->getExpression()->traverse(this);
1623
1624 switch (node->getFlowOp()) {
1625 case glslang::EOpKill:
1626 builder.makeDiscard();
1627 break;
1628 case glslang::EOpBreak:
1629 if (breakForLoop.top())
1630 builder.createLoopExit();
1631 else
1632 builder.addSwitchBreak();
1633 break;
1634 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001635 builder.createLoopContinue();
1636 break;
1637 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001638 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001639 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001640 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001641 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001642
1643 builder.clearAccessChain();
1644 break;
1645
1646 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001647 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001648 break;
1649 }
1650
1651 return false;
1652}
1653
1654spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1655{
1656 // First, steer off constants, which are not SPIR-V variables, but
1657 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001658 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001659 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001660 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001661 }
1662
1663 // Now, handle actual variables
1664 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1665 spv::Id spvType = convertGlslangToSpvType(node->getType());
1666
1667 const char* name = node->getName().c_str();
1668 if (glslang::IsAnonymous(name))
1669 name = "";
1670
1671 return builder.createVariable(storageClass, spvType, name);
1672}
1673
1674// Return type Id of the sampled type.
1675spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1676{
1677 switch (sampler.type) {
1678 case glslang::EbtFloat: return builder.makeFloatType(32);
1679 case glslang::EbtInt: return builder.makeIntType(32);
1680 case glslang::EbtUint: return builder.makeUintType(32);
1681 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001682 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001683 return builder.makeFloatType(32);
1684 }
1685}
1686
John Kessenich3ac051e2015-12-20 11:29:16 -07001687// Convert from a glslang type to an SPV type, by calling into a
1688// recursive version of this function. This establishes the inherited
1689// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001690spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1691{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001692 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001693}
1694
1695// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001696// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001697spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001698{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001699 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001700
1701 switch (type.getBasicType()) {
1702 case glslang::EbtVoid:
1703 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001704 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001705 break;
1706 case glslang::EbtFloat:
1707 spvType = builder.makeFloatType(32);
1708 break;
1709 case glslang::EbtDouble:
1710 spvType = builder.makeFloatType(64);
1711 break;
1712 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001713 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1714 // a 32-bit int where non-0 means true.
1715 if (explicitLayout != glslang::ElpNone)
1716 spvType = builder.makeUintType(32);
1717 else
1718 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001719 break;
1720 case glslang::EbtInt:
1721 spvType = builder.makeIntType(32);
1722 break;
1723 case glslang::EbtUint:
1724 spvType = builder.makeUintType(32);
1725 break;
John Kessenich426394d2015-07-23 10:22:48 -06001726 case glslang::EbtAtomicUint:
1727 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1728 spvType = builder.makeUintType(32);
1729 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001730 case glslang::EbtSampler:
1731 {
1732 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001733 if (sampler.sampler) {
1734 // pure sampler
1735 spvType = builder.makeSamplerType();
1736 } else {
1737 // an image is present, make its type
1738 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1739 sampler.image ? 2 : 1, TranslateImageFormat(type));
1740 if (sampler.combined) {
1741 // already has both image and sampler, make the combined type
1742 spvType = builder.makeSampledImageType(spvType);
1743 }
John Kessenich55e7d112015-11-15 21:33:39 -07001744 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001745 }
John Kessenich140f3df2015-06-26 16:58:36 -06001746 break;
1747 case glslang::EbtStruct:
1748 case glslang::EbtBlock:
1749 {
1750 // If we've seen this struct type, return it
1751 const glslang::TTypeList* glslangStruct = type.getStruct();
1752 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001753
1754 // Try to share structs for different layouts, but not yet for other
1755 // kinds of qualification (primarily not yet including interpolant qualification).
1756 if (! HasNonLayoutQualifiers(qualifier))
1757 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1758 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001759 break;
1760
1761 // else, we haven't seen it...
1762
1763 // Create a vector of struct types for SPIR-V to consume
1764 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1765 if (type.getBasicType() == glslang::EbtBlock)
1766 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001767 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001768 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1769 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1770 if (glslangType.hiddenMember()) {
1771 ++memberDelta;
1772 if (type.getBasicType() == glslang::EbtBlock)
1773 memberRemapper[glslangStruct][i] = -1;
1774 } else {
1775 if (type.getBasicType() == glslang::EbtBlock)
1776 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001777 // modify just this child's view of the qualifier
1778 glslang::TQualifier subQualifier = glslangType.getQualifier();
1779 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001780
1781 // manually inherit location; it's more complex
1782 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1783 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1784 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001785 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001786
1787 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001788 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001789 }
1790 }
1791
1792 // Make the SPIR-V type
1793 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001794 if (! HasNonLayoutQualifiers(qualifier))
1795 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001796
1797 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001798 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001799 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001800 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1801 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1802 int member = i;
1803 if (type.getBasicType() == glslang::EbtBlock)
1804 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001805
John Kesseniche0b6cad2015-12-24 10:30:13 -07001806 // modify just this child's view of the qualifier
1807 glslang::TQualifier subQualifier = glslangType.getQualifier();
1808 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001809
John Kessenich140f3df2015-06-26 16:58:36 -06001810 // using -1 above to indicate a hidden member
1811 if (member >= 0) {
1812 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001813 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001814 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001815 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1816 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001817
Rex Xu1da878f2016-02-21 20:59:01 +08001818 if (qualifier.storage == glslang::EvqBuffer) {
1819 std::vector<spv::Decoration> memory;
1820 TranslateMemoryDecoration(subQualifier, memory);
1821 for (unsigned int i = 0; i < memory.size(); ++i)
1822 addMemberDecoration(spvType, member, memory[i]);
1823 }
1824
John Kessenich09677482016-02-19 12:21:50 -07001825 // compute location decoration; tricky based on whether inheritance is at play
1826 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1827 // probably move to the linker stage of the front end proper, and just have the
1828 // answer sitting already distributed throughout the individual member locations.
1829 int location = -1; // will only decorate if present or inherited
1830 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1831 location = subQualifier.layoutLocation;
1832 else if (qualifier.hasLocation()) // inheritance
1833 location = qualifier.layoutLocation + locationOffset;
1834 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001835 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001836 if (location >= 0)
1837 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1838
1839 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001840 if (glslangType.getQualifier().hasComponent())
1841 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1842 if (glslangType.getQualifier().hasXfbOffset())
1843 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001844 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001845 // figure out what to do with offset, which is accumulating
1846 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001847 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001848 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001849 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001850 offset = nextOffset;
1851 }
John Kessenich140f3df2015-06-26 16:58:36 -06001852
John Kessenichf85e8062015-12-19 13:57:10 -07001853 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001854 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001855
John Kessenich140f3df2015-06-26 16:58:36 -06001856 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001857 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1858 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001859 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001860 }
1861 }
1862
1863 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001864 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001865 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001866 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001867 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001868 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001869 }
John Kessenich140f3df2015-06-26 16:58:36 -06001870 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001871 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001872 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001873 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001874 if (type.getQualifier().hasXfbBuffer())
1875 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1876 }
1877 }
1878 break;
1879 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001880 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001881 break;
1882 }
1883
1884 if (type.isMatrix())
1885 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1886 else {
1887 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1888 if (type.getVectorSize() > 1)
1889 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1890 }
1891
1892 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001893 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1894
John Kessenichc9a80832015-09-12 12:17:44 -06001895 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001896 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001897 // We need to decorate array strides for types needing explicit layout, except blocks.
1898 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001899 // Use a dummy glslang type for querying internal strides of
1900 // arrays of arrays, but using just a one-dimensional array.
1901 glslang::TType simpleArrayType(type, 0); // deference type of the array
1902 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1903 simpleArrayType.getArraySizes().dereference();
1904
1905 // Will compute the higher-order strides here, rather than making a whole
1906 // pile of types and doing repetitive recursion on their contents.
1907 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1908 }
John Kessenichf8842e52016-01-04 19:22:56 -07001909
1910 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001911 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001912 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001913 if (stride > 0)
1914 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001915 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001916 }
1917 } else {
1918 // single-dimensional array, and don't yet have stride
1919
John Kessenichf8842e52016-01-04 19:22:56 -07001920 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001921 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1922 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001923 }
John Kessenich31ed4832015-09-09 17:51:38 -06001924
John Kessenichc9a80832015-09-12 12:17:44 -06001925 // Do the outer dimension, which might not be known for a runtime-sized array
1926 if (type.isRuntimeSizedArray()) {
1927 spvType = builder.makeRuntimeArray(spvType);
1928 } else {
1929 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001930 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001931 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001932 if (stride > 0)
1933 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001934 }
1935
1936 return spvType;
1937}
1938
John Kessenich6c292d32016-02-15 20:58:50 -07001939// Turn the expression forming the array size into an id.
1940// This is not quite trivial, because of specialization constants.
1941// Sometimes, a raw constant is turned into an Id, and sometimes
1942// a specialization constant expression is.
1943spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1944{
1945 // First, see if this is sized with a node, meaning a specialization constant:
1946 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1947 if (specNode != nullptr) {
1948 builder.clearAccessChain();
qining4c912612016-04-01 10:35:16 -04001949 SpecConstantOpModeGuard set_to_spec_const_mode(&builder);
John Kessenich6c292d32016-02-15 20:58:50 -07001950 specNode->traverse(this);
1951 return accessChainLoad(specNode->getAsTyped()->getType());
1952 }
1953
1954 // Otherwise, need a compile-time (front end) size, get it:
1955 int size = arraySizes.getDimSize(dim);
1956 assert(size > 0);
1957 return builder.makeUintConstant(size);
1958}
1959
John Kessenich103bef92016-02-08 21:38:15 -07001960// Wrap the builder's accessChainLoad to:
1961// - localize handling of RelaxedPrecision
1962// - use the SPIR-V inferred type instead of another conversion of the glslang type
1963// (avoids unnecessary work and possible type punning for structures)
1964// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001965spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1966{
John Kessenich103bef92016-02-08 21:38:15 -07001967 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1968 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1969
1970 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08001971 if (type.getBasicType() == glslang::EbtBool) {
1972 if (builder.isScalarType(nominalTypeId)) {
1973 // Conversion for bool
1974 spv::Id boolType = builder.makeBoolType();
1975 if (nominalTypeId != boolType)
1976 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
1977 } else if (builder.isVectorType(nominalTypeId)) {
1978 // Conversion for bvec
1979 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1980 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1981 if (nominalTypeId != bvecType)
1982 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
1983 }
1984 }
John Kessenich103bef92016-02-08 21:38:15 -07001985
1986 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07001987}
1988
Rex Xu27253232016-02-23 17:51:09 +08001989// Wrap the builder's accessChainStore to:
1990// - do conversion of concrete to abstract type
1991void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
1992{
1993 // Need to convert to abstract types when necessary
1994 if (type.getBasicType() == glslang::EbtBool) {
1995 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1996
1997 if (builder.isScalarType(nominalTypeId)) {
1998 // Conversion for bool
1999 spv::Id boolType = builder.makeBoolType();
2000 if (nominalTypeId != boolType) {
2001 spv::Id zero = builder.makeUintConstant(0);
2002 spv::Id one = builder.makeUintConstant(1);
2003 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2004 }
2005 } else if (builder.isVectorType(nominalTypeId)) {
2006 // Conversion for bvec
2007 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2008 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2009 if (nominalTypeId != bvecType) {
2010 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2011 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2012 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2013 }
2014 }
2015 }
2016
2017 builder.accessChainStore(rvalue);
2018}
2019
John Kessenichf85e8062015-12-19 13:57:10 -07002020// Decide whether or not this type should be
2021// decorated with offsets and strides, and if so
2022// whether std140 or std430 rules should be applied.
2023glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002024{
John Kessenichf85e8062015-12-19 13:57:10 -07002025 // has to be a block
2026 if (type.getBasicType() != glslang::EbtBlock)
2027 return glslang::ElpNone;
2028
2029 // has to be a uniform or buffer block
2030 if (type.getQualifier().storage != glslang::EvqUniform &&
2031 type.getQualifier().storage != glslang::EvqBuffer)
2032 return glslang::ElpNone;
2033
2034 // return the layout to use
2035 switch (type.getQualifier().layoutPacking) {
2036 case glslang::ElpStd140:
2037 case glslang::ElpStd430:
2038 return type.getQualifier().layoutPacking;
2039 default:
2040 return glslang::ElpNone;
2041 }
John Kessenich31ed4832015-09-09 17:51:38 -06002042}
2043
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002044// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002045int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002046{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002047 int size;
John Kessenich49987892015-12-29 17:11:44 -07002048 int stride;
2049 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002050
2051 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002052}
2053
John Kessenich49987892015-12-29 17:11:44 -07002054// 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 -07002055// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002056int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002057{
John Kessenich49987892015-12-29 17:11:44 -07002058 glslang::TType elementType;
2059 elementType.shallowCopy(matrixType);
2060 elementType.clearArraySizes();
2061
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002062 int size;
John Kessenich49987892015-12-29 17:11:44 -07002063 int stride;
2064 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2065
2066 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002067}
2068
John Kessenich5e4b1242015-08-06 22:53:06 -06002069// Given a member type of a struct, realign the current offset for it, and compute
2070// the next (not yet aligned) offset for the next member, which will get aligned
2071// on the next call.
2072// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2073// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2074// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002075void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002076 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002077{
2078 // this will get a positive value when deemed necessary
2079 nextOffset = -1;
2080
John Kessenich5e4b1242015-08-06 22:53:06 -06002081 // override anything in currentOffset with user-set offset
2082 if (memberType.getQualifier().hasOffset())
2083 currentOffset = memberType.getQualifier().layoutOffset;
2084
2085 // It could be that current linker usage in glslang updated all the layoutOffset,
2086 // in which case the following code does not matter. But, that's not quite right
2087 // once cross-compilation unit GLSL validation is done, as the original user
2088 // settings are needed in layoutOffset, and then the following will come into play.
2089
John Kessenichf85e8062015-12-19 13:57:10 -07002090 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002091 if (! memberType.getQualifier().hasOffset())
2092 currentOffset = -1;
2093
2094 return;
2095 }
2096
John Kessenichf85e8062015-12-19 13:57:10 -07002097 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002098 if (currentOffset < 0)
2099 currentOffset = 0;
2100
2101 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2102 // but possibly not yet correctly aligned.
2103
2104 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002105 int dummyStride;
2106 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002107 glslang::RoundToPow2(currentOffset, memberAlignment);
2108 nextOffset = currentOffset + memberSize;
2109}
2110
John Kessenich140f3df2015-06-26 16:58:36 -06002111bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2112{
John Kessenich4d65ee32016-03-12 18:17:47 -07002113 // have to ignore mangling and just look at the base name
2114 int firstOpen = node->getName().find('(');
2115 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002116}
2117
2118// Make all the functions, skeletally, without actually visiting their bodies.
2119void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2120{
2121 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2122 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2123 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2124 continue;
2125
2126 // We're on a user function. Set up the basic interface for the function now,
2127 // so that it's available to call.
2128 // Translating the body will happen later.
2129 //
2130 // Typically (except for a "const in" parameter), an address will be passed to the
2131 // function. What it is an address of varies:
2132 //
2133 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2134 // so that write needs to be to a copy, hence the address of a copy works.
2135 //
2136 // - "const in" parameters can just be the r-value, as no writes need occur.
2137 //
2138 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2139 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2140
2141 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002142 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002143 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2144
2145 for (int p = 0; p < (int)parameters.size(); ++p) {
2146 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2147 spv::Id typeId = convertGlslangToSpvType(paramType);
2148 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2149 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2150 else
2151 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002152 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002153 paramTypes.push_back(typeId);
2154 }
2155
2156 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002157 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2158 convertGlslangToSpvType(glslFunction->getType()),
2159 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002160
2161 // Track function to emit/call later
2162 functionMap[glslFunction->getName().c_str()] = function;
2163
2164 // Set the parameter id's
2165 for (int p = 0; p < (int)parameters.size(); ++p) {
2166 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2167 // give a name too
2168 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2169 }
2170 }
2171}
2172
2173// Process all the initializers, while skipping the functions and link objects
2174void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2175{
2176 builder.setBuildPoint(shaderEntry->getLastBlock());
2177 for (int i = 0; i < (int)initializers.size(); ++i) {
2178 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2179 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2180
2181 // We're on a top-level node that's not a function. Treat as an initializer, whose
2182 // code goes into the beginning of main.
2183 initializer->traverse(this);
2184 }
2185 }
2186}
2187
2188// Process all the functions, while skipping initializers.
2189void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2190{
2191 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2192 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2193 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2194 node->traverse(this);
2195 }
2196}
2197
2198void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2199{
2200 // SPIR-V functions should already be in the functionMap from the prepass
2201 // that called makeFunctions().
2202 spv::Function* function = functionMap[node->getName().c_str()];
2203 spv::Block* functionBlock = function->getEntryBlock();
2204 builder.setBuildPoint(functionBlock);
2205}
2206
Rex Xu04db3f52015-09-16 11:44:02 +08002207void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002208{
Rex Xufc618912015-09-09 16:42:49 +08002209 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002210
2211 glslang::TSampler sampler = {};
2212 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002213 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002214 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2215 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2216 }
2217
John Kessenich140f3df2015-06-26 16:58:36 -06002218 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2219 builder.clearAccessChain();
2220 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002221
2222 // Special case l-value operands
2223 bool lvalue = false;
2224 switch (node.getOp()) {
2225 case glslang::EOpImageAtomicAdd:
2226 case glslang::EOpImageAtomicMin:
2227 case glslang::EOpImageAtomicMax:
2228 case glslang::EOpImageAtomicAnd:
2229 case glslang::EOpImageAtomicOr:
2230 case glslang::EOpImageAtomicXor:
2231 case glslang::EOpImageAtomicExchange:
2232 case glslang::EOpImageAtomicCompSwap:
2233 if (i == 0)
2234 lvalue = true;
2235 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002236 case glslang::EOpSparseImageLoad:
2237 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2238 lvalue = true;
2239 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002240 case glslang::EOpSparseTexture:
2241 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2242 lvalue = true;
2243 break;
2244 case glslang::EOpSparseTextureClamp:
2245 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2246 lvalue = true;
2247 break;
2248 case glslang::EOpSparseTextureLod:
2249 case glslang::EOpSparseTextureOffset:
2250 if (i == 3)
2251 lvalue = true;
2252 break;
2253 case glslang::EOpSparseTextureFetch:
2254 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2255 lvalue = true;
2256 break;
2257 case glslang::EOpSparseTextureFetchOffset:
2258 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2259 lvalue = true;
2260 break;
2261 case glslang::EOpSparseTextureLodOffset:
2262 case glslang::EOpSparseTextureGrad:
2263 case glslang::EOpSparseTextureOffsetClamp:
2264 if (i == 4)
2265 lvalue = true;
2266 break;
2267 case glslang::EOpSparseTextureGradOffset:
2268 case glslang::EOpSparseTextureGradClamp:
2269 if (i == 5)
2270 lvalue = true;
2271 break;
2272 case glslang::EOpSparseTextureGradOffsetClamp:
2273 if (i == 6)
2274 lvalue = true;
2275 break;
2276 case glslang::EOpSparseTextureGather:
2277 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2278 lvalue = true;
2279 break;
2280 case glslang::EOpSparseTextureGatherOffset:
2281 case glslang::EOpSparseTextureGatherOffsets:
2282 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2283 lvalue = true;
2284 break;
Rex Xufc618912015-09-09 16:42:49 +08002285 default:
2286 break;
2287 }
2288
Rex Xu6b86d492015-09-16 17:48:22 +08002289 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002290 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002291 else
John Kessenich32cfd492016-02-02 12:37:46 -07002292 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002293 }
2294}
2295
John Kessenichfc51d282015-08-19 13:34:18 -06002296void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002297{
John Kessenichfc51d282015-08-19 13:34:18 -06002298 builder.clearAccessChain();
2299 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002300 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002301}
John Kessenich140f3df2015-06-26 16:58:36 -06002302
John Kessenichfc51d282015-08-19 13:34:18 -06002303spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2304{
Rex Xufc618912015-09-09 16:42:49 +08002305 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002306 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002307 }
2308
John Kessenichfc51d282015-08-19 13:34:18 -06002309 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002310 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2311 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2312 std::vector<spv::Id> arguments;
2313 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002314 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002315 else
2316 translateArguments(*node->getAsUnaryNode(), arguments);
2317 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2318
2319 spv::Builder::TextureParameters params = { };
2320 params.sampler = arguments[0];
2321
Rex Xu04db3f52015-09-16 11:44:02 +08002322 glslang::TCrackedTextureOp cracked;
2323 node->crackTexture(sampler, cracked);
2324
John Kessenichfc51d282015-08-19 13:34:18 -06002325 // Check for queries
2326 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002327 // a sampled image needs to have the image extracted first
2328 if (builder.isSampledImage(params.sampler))
2329 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002330 switch (node->getOp()) {
2331 case glslang::EOpImageQuerySize:
2332 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002333 if (arguments.size() > 1) {
2334 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002335 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002336 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002337 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002338 case glslang::EOpImageQuerySamples:
2339 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002340 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002341 case glslang::EOpTextureQueryLod:
2342 params.coords = arguments[1];
2343 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2344 case glslang::EOpTextureQueryLevels:
2345 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002346 case glslang::EOpSparseTexelsResident:
2347 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002348 default:
2349 assert(0);
2350 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002351 }
John Kessenich140f3df2015-06-26 16:58:36 -06002352 }
2353
Rex Xufc618912015-09-09 16:42:49 +08002354 // Check for image functions other than queries
2355 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002356 std::vector<spv::Id> operands;
2357 auto opIt = arguments.begin();
2358 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002359
2360 // Handle subpass operations
2361 // TODO: GLSL should change to have the "MS" only on the type rather than the
2362 // built-in function.
2363 if (cracked.subpass) {
2364 // add on the (0,0) coordinate
2365 spv::Id zero = builder.makeIntConstant(0);
2366 std::vector<spv::Id> comps;
2367 comps.push_back(zero);
2368 comps.push_back(zero);
2369 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2370 if (sampler.ms) {
2371 operands.push_back(spv::ImageOperandsSampleMask);
2372 operands.push_back(*(opIt++));
2373 }
2374 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2375 }
2376
John Kessenich56bab042015-09-16 10:54:31 -06002377 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002378 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002379 if (sampler.ms) {
2380 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002381 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002382 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002383 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2384 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002385 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002386 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002387 if (sampler.ms) {
2388 operands.push_back(*(opIt + 1));
2389 operands.push_back(spv::ImageOperandsSampleMask);
2390 operands.push_back(*opIt);
2391 } else
2392 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002393 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002394 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2395 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002396 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002397 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2398 builder.addCapability(spv::CapabilitySparseResidency);
2399 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2400 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2401
2402 if (sampler.ms) {
2403 operands.push_back(spv::ImageOperandsSampleMask);
2404 operands.push_back(*opIt++);
2405 }
2406
2407 // Create the return type that was a special structure
2408 spv::Id texelOut = *opIt;
2409 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2410 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2411 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2412
2413 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2414
2415 // Decode the return type
2416 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2417 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002418 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002419 // Process image atomic operations
2420
2421 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2422 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002423 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002424
Rex Xufc618912015-09-09 16:42:49 +08002425 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002426 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002427
2428 std::vector<spv::Id> operands;
2429 operands.push_back(pointer);
2430 for (; opIt != arguments.end(); ++opIt)
2431 operands.push_back(*opIt);
2432
Rex Xu04db3f52015-09-16 11:44:02 +08002433 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002434 }
2435 }
2436
2437 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002438 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002439 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2440
John Kessenichfc51d282015-08-19 13:34:18 -06002441 // check for bias argument
2442 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002443 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002444 int nonBiasArgCount = 2;
2445 if (cracked.offset)
2446 ++nonBiasArgCount;
2447 if (cracked.grad)
2448 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002449 if (cracked.lodClamp)
2450 ++nonBiasArgCount;
2451 if (sparse)
2452 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002453
2454 if ((int)arguments.size() > nonBiasArgCount)
2455 bias = true;
2456 }
2457
John Kessenichfc51d282015-08-19 13:34:18 -06002458 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002459
John Kessenichfc51d282015-08-19 13:34:18 -06002460 params.coords = arguments[1];
2461 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002462 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002463
2464 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002465 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002466 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002467 ++extraArgs;
2468 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002469 params.Dref = arguments[2];
2470 ++extraArgs;
2471 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002472 std::vector<spv::Id> indexes;
2473 int comp;
2474 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002475 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002476 else
2477 comp = builder.getNumComponents(params.coords) - 1;
2478 indexes.push_back(comp);
2479 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2480 }
2481 if (cracked.lod) {
2482 params.lod = arguments[2];
2483 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002484 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2485 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2486 noImplicitLod = true;
2487 }
2488 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002489 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002490 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002491 }
2492 if (cracked.grad) {
2493 params.gradX = arguments[2 + extraArgs];
2494 params.gradY = arguments[3 + extraArgs];
2495 extraArgs += 2;
2496 }
John Kessenich55e7d112015-11-15 21:33:39 -07002497 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002498 params.offset = arguments[2 + extraArgs];
2499 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002500 } else if (cracked.offsets) {
2501 params.offsets = arguments[2 + extraArgs];
2502 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002503 }
Rex Xu48edadf2015-12-31 16:11:41 +08002504 if (cracked.lodClamp) {
2505 params.lodClamp = arguments[2 + extraArgs];
2506 ++extraArgs;
2507 }
2508 if (sparse) {
2509 params.texelOut = arguments[2 + extraArgs];
2510 ++extraArgs;
2511 }
John Kessenichfc51d282015-08-19 13:34:18 -06002512 if (bias) {
2513 params.bias = arguments[2 + extraArgs];
2514 ++extraArgs;
2515 }
John Kessenich55e7d112015-11-15 21:33:39 -07002516 if (cracked.gather && ! sampler.shadow) {
2517 // default component is 0, if missing, otherwise an argument
2518 if (2 + extraArgs < (int)arguments.size()) {
2519 params.comp = arguments[2 + extraArgs];
2520 ++extraArgs;
2521 } else {
2522 params.comp = builder.makeIntConstant(0);
2523 }
2524 }
John Kessenichfc51d282015-08-19 13:34:18 -06002525
John Kessenich019f08f2016-02-15 15:40:42 -07002526 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002527}
2528
2529spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2530{
2531 // Grab the function's pointer from the previously created function
2532 spv::Function* function = functionMap[node->getName().c_str()];
2533 if (! function)
2534 return 0;
2535
2536 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2537 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2538
2539 // See comments in makeFunctions() for details about the semantics for parameter passing.
2540 //
2541 // These imply we need a four step process:
2542 // 1. Evaluate the arguments
2543 // 2. Allocate and make copies of in, out, and inout arguments
2544 // 3. Make the call
2545 // 4. Copy back the results
2546
2547 // 1. Evaluate the arguments
2548 std::vector<spv::Builder::AccessChain> lValues;
2549 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002550 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002551 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2552 // build l-value
2553 builder.clearAccessChain();
2554 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002555 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002556 // keep outputs as l-values, evaluate input-only as r-values
2557 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2558 // save l-value
2559 lValues.push_back(builder.getAccessChain());
2560 } else {
2561 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002562 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002563 }
2564 }
2565
2566 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2567 // copy the original into that space.
2568 //
2569 // Also, build up the list of actual arguments to pass in for the call
2570 int lValueCount = 0;
2571 int rValueCount = 0;
2572 std::vector<spv::Id> spvArgs;
2573 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2574 spv::Id arg;
2575 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2576 // need space to hold the copy
2577 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2578 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2579 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2580 // need to copy the input into output space
2581 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002582 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002583 builder.createStore(copy, arg);
2584 }
2585 ++lValueCount;
2586 } else {
2587 arg = rValues[rValueCount];
2588 ++rValueCount;
2589 }
2590 spvArgs.push_back(arg);
2591 }
2592
2593 // 3. Make the call.
2594 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002595 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002596
2597 // 4. Copy back out an "out" arguments.
2598 lValueCount = 0;
2599 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2600 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2601 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2602 spv::Id copy = builder.createLoad(spvArgs[a]);
2603 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002604 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002605 }
2606 ++lValueCount;
2607 }
2608 }
2609
2610 return result;
2611}
2612
2613// Translate AST operation to SPV operation, already having SPV-based operands/types.
2614spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2615 spv::Id typeId, spv::Id left, spv::Id right,
2616 glslang::TBasicType typeProxy, bool reduceComparison)
2617{
2618 bool isUnsigned = typeProxy == glslang::EbtUint;
2619 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2620
2621 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002622 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002623 bool comparison = false;
2624
2625 switch (op) {
2626 case glslang::EOpAdd:
2627 case glslang::EOpAddAssign:
2628 if (isFloat)
2629 binOp = spv::OpFAdd;
2630 else
2631 binOp = spv::OpIAdd;
2632 break;
2633 case glslang::EOpSub:
2634 case glslang::EOpSubAssign:
2635 if (isFloat)
2636 binOp = spv::OpFSub;
2637 else
2638 binOp = spv::OpISub;
2639 break;
2640 case glslang::EOpMul:
2641 case glslang::EOpMulAssign:
2642 if (isFloat)
2643 binOp = spv::OpFMul;
2644 else
2645 binOp = spv::OpIMul;
2646 break;
2647 case glslang::EOpVectorTimesScalar:
2648 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002649 if (isFloat) {
2650 if (builder.isVector(right))
2651 std::swap(left, right);
2652 assert(builder.isScalar(right));
2653 needMatchingVectors = false;
2654 binOp = spv::OpVectorTimesScalar;
2655 } else
2656 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002657 break;
2658 case glslang::EOpVectorTimesMatrix:
2659 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002660 binOp = spv::OpVectorTimesMatrix;
2661 break;
2662 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002663 binOp = spv::OpMatrixTimesVector;
2664 break;
2665 case glslang::EOpMatrixTimesScalar:
2666 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002667 binOp = spv::OpMatrixTimesScalar;
2668 break;
2669 case glslang::EOpMatrixTimesMatrix:
2670 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002671 binOp = spv::OpMatrixTimesMatrix;
2672 break;
2673 case glslang::EOpOuterProduct:
2674 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002675 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002676 break;
2677
2678 case glslang::EOpDiv:
2679 case glslang::EOpDivAssign:
2680 if (isFloat)
2681 binOp = spv::OpFDiv;
2682 else if (isUnsigned)
2683 binOp = spv::OpUDiv;
2684 else
2685 binOp = spv::OpSDiv;
2686 break;
2687 case glslang::EOpMod:
2688 case glslang::EOpModAssign:
2689 if (isFloat)
2690 binOp = spv::OpFMod;
2691 else if (isUnsigned)
2692 binOp = spv::OpUMod;
2693 else
2694 binOp = spv::OpSMod;
2695 break;
2696 case glslang::EOpRightShift:
2697 case glslang::EOpRightShiftAssign:
2698 if (isUnsigned)
2699 binOp = spv::OpShiftRightLogical;
2700 else
2701 binOp = spv::OpShiftRightArithmetic;
2702 break;
2703 case glslang::EOpLeftShift:
2704 case glslang::EOpLeftShiftAssign:
2705 binOp = spv::OpShiftLeftLogical;
2706 break;
2707 case glslang::EOpAnd:
2708 case glslang::EOpAndAssign:
2709 binOp = spv::OpBitwiseAnd;
2710 break;
2711 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002712 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002713 binOp = spv::OpLogicalAnd;
2714 break;
2715 case glslang::EOpInclusiveOr:
2716 case glslang::EOpInclusiveOrAssign:
2717 binOp = spv::OpBitwiseOr;
2718 break;
2719 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002720 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002721 binOp = spv::OpLogicalOr;
2722 break;
2723 case glslang::EOpExclusiveOr:
2724 case glslang::EOpExclusiveOrAssign:
2725 binOp = spv::OpBitwiseXor;
2726 break;
2727 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002728 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002729 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002730 break;
2731
2732 case glslang::EOpLessThan:
2733 case glslang::EOpGreaterThan:
2734 case glslang::EOpLessThanEqual:
2735 case glslang::EOpGreaterThanEqual:
2736 case glslang::EOpEqual:
2737 case glslang::EOpNotEqual:
2738 case glslang::EOpVectorEqual:
2739 case glslang::EOpVectorNotEqual:
2740 comparison = true;
2741 break;
2742 default:
2743 break;
2744 }
2745
John Kessenich7c1aa102015-10-15 13:29:11 -06002746 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002747 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002748 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002749 if (builder.isMatrix(left) || builder.isMatrix(right))
2750 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002751
2752 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002753 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002754 builder.promoteScalar(precision, left, right);
2755
John Kessenich32cfd492016-02-02 12:37:46 -07002756 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002757 }
2758
2759 if (! comparison)
2760 return 0;
2761
John Kessenich7c1aa102015-10-15 13:29:11 -06002762 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002763
2764 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2765 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2766
John Kessenich22118352015-12-21 20:54:09 -07002767 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002768 }
2769
2770 switch (op) {
2771 case glslang::EOpLessThan:
2772 if (isFloat)
2773 binOp = spv::OpFOrdLessThan;
2774 else if (isUnsigned)
2775 binOp = spv::OpULessThan;
2776 else
2777 binOp = spv::OpSLessThan;
2778 break;
2779 case glslang::EOpGreaterThan:
2780 if (isFloat)
2781 binOp = spv::OpFOrdGreaterThan;
2782 else if (isUnsigned)
2783 binOp = spv::OpUGreaterThan;
2784 else
2785 binOp = spv::OpSGreaterThan;
2786 break;
2787 case glslang::EOpLessThanEqual:
2788 if (isFloat)
2789 binOp = spv::OpFOrdLessThanEqual;
2790 else if (isUnsigned)
2791 binOp = spv::OpULessThanEqual;
2792 else
2793 binOp = spv::OpSLessThanEqual;
2794 break;
2795 case glslang::EOpGreaterThanEqual:
2796 if (isFloat)
2797 binOp = spv::OpFOrdGreaterThanEqual;
2798 else if (isUnsigned)
2799 binOp = spv::OpUGreaterThanEqual;
2800 else
2801 binOp = spv::OpSGreaterThanEqual;
2802 break;
2803 case glslang::EOpEqual:
2804 case glslang::EOpVectorEqual:
2805 if (isFloat)
2806 binOp = spv::OpFOrdEqual;
2807 else
2808 binOp = spv::OpIEqual;
2809 break;
2810 case glslang::EOpNotEqual:
2811 case glslang::EOpVectorNotEqual:
2812 if (isFloat)
2813 binOp = spv::OpFOrdNotEqual;
2814 else
2815 binOp = spv::OpINotEqual;
2816 break;
2817 default:
2818 break;
2819 }
2820
John Kessenich32cfd492016-02-02 12:37:46 -07002821 if (binOp != spv::OpNop)
2822 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002823
2824 return 0;
2825}
2826
John Kessenich04bb8a02015-12-12 12:28:14 -07002827//
2828// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2829// These can be any of:
2830//
2831// matrix * scalar
2832// scalar * matrix
2833// matrix * matrix linear algebraic
2834// matrix * vector
2835// vector * matrix
2836// matrix * matrix componentwise
2837// matrix op matrix op in {+, -, /}
2838// matrix op scalar op in {+, -, /}
2839// scalar op matrix op in {+, -, /}
2840//
2841spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2842{
2843 bool firstClass = true;
2844
2845 // First, handle first-class matrix operations (* and matrix/scalar)
2846 switch (op) {
2847 case spv::OpFDiv:
2848 if (builder.isMatrix(left) && builder.isScalar(right)) {
2849 // turn matrix / scalar into a multiply...
2850 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2851 op = spv::OpMatrixTimesScalar;
2852 } else
2853 firstClass = false;
2854 break;
2855 case spv::OpMatrixTimesScalar:
2856 if (builder.isMatrix(right))
2857 std::swap(left, right);
2858 assert(builder.isScalar(right));
2859 break;
2860 case spv::OpVectorTimesMatrix:
2861 assert(builder.isVector(left));
2862 assert(builder.isMatrix(right));
2863 break;
2864 case spv::OpMatrixTimesVector:
2865 assert(builder.isMatrix(left));
2866 assert(builder.isVector(right));
2867 break;
2868 case spv::OpMatrixTimesMatrix:
2869 assert(builder.isMatrix(left));
2870 assert(builder.isMatrix(right));
2871 break;
2872 default:
2873 firstClass = false;
2874 break;
2875 }
2876
John Kessenich32cfd492016-02-02 12:37:46 -07002877 if (firstClass)
2878 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002879
2880 // Handle component-wise +, -, *, and / for all combinations of type.
2881 // The result type of all of them is the same type as the (a) matrix operand.
2882 // The algorithm is to:
2883 // - break the matrix(es) into vectors
2884 // - smear any scalar to a vector
2885 // - do vector operations
2886 // - make a matrix out the vector results
2887 switch (op) {
2888 case spv::OpFAdd:
2889 case spv::OpFSub:
2890 case spv::OpFDiv:
2891 case spv::OpFMul:
2892 {
2893 // one time set up...
2894 bool leftMat = builder.isMatrix(left);
2895 bool rightMat = builder.isMatrix(right);
2896 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2897 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2898 spv::Id scalarType = builder.getScalarTypeId(typeId);
2899 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2900 std::vector<spv::Id> results;
2901 spv::Id smearVec = spv::NoResult;
2902 if (builder.isScalar(left))
2903 smearVec = builder.smearScalar(precision, left, vecType);
2904 else if (builder.isScalar(right))
2905 smearVec = builder.smearScalar(precision, right, vecType);
2906
2907 // do each vector op
2908 for (unsigned int c = 0; c < numCols; ++c) {
2909 std::vector<unsigned int> indexes;
2910 indexes.push_back(c);
2911 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2912 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2913 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2914 builder.setPrecision(results.back(), precision);
2915 }
2916
2917 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002918 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002919 }
2920 default:
2921 assert(0);
2922 return spv::NoResult;
2923 }
2924}
2925
Rex Xu04db3f52015-09-16 11:44:02 +08002926spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06002927{
2928 spv::Op unaryOp = spv::OpNop;
2929 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002930 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002931 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002932
2933 switch (op) {
2934 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002935 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002936 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002937 if (builder.isMatrixType(typeId))
2938 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2939 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002940 unaryOp = spv::OpSNegate;
2941 break;
2942
2943 case glslang::EOpLogicalNot:
2944 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002945 unaryOp = spv::OpLogicalNot;
2946 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002947 case glslang::EOpBitwiseNot:
2948 unaryOp = spv::OpNot;
2949 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002950
John Kessenich140f3df2015-06-26 16:58:36 -06002951 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002952 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002953 break;
2954 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002955 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002956 break;
2957 case glslang::EOpTranspose:
2958 unaryOp = spv::OpTranspose;
2959 break;
2960
2961 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002962 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002963 break;
2964 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002965 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002966 break;
2967 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002968 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002969 break;
2970 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002971 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002972 break;
2973 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002974 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002975 break;
2976 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002977 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002978 break;
2979 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002980 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002981 break;
2982 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002983 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002984 break;
2985
2986 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002987 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002988 break;
2989 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002990 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002991 break;
2992 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002993 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002994 break;
2995 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002996 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002997 break;
2998 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002999 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003000 break;
3001 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003002 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003003 break;
3004
3005 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003006 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003007 break;
3008 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003009 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003010 break;
3011
3012 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003013 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003014 break;
3015 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003016 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003017 break;
3018 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003019 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003020 break;
3021 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003022 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003023 break;
3024 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003025 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003026 break;
3027 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003028 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003029 break;
3030
3031 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003032 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003033 break;
3034 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003035 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003036 break;
3037 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003038 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003039 break;
3040 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003041 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003042 break;
3043 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003044 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003045 break;
3046 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003047 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003048 break;
3049
3050 case glslang::EOpIsNan:
3051 unaryOp = spv::OpIsNan;
3052 break;
3053 case glslang::EOpIsInf:
3054 unaryOp = spv::OpIsInf;
3055 break;
3056
Rex Xucbc426e2015-12-15 16:03:10 +08003057 case glslang::EOpFloatBitsToInt:
3058 case glslang::EOpFloatBitsToUint:
3059 case glslang::EOpIntBitsToFloat:
3060 case glslang::EOpUintBitsToFloat:
3061 unaryOp = spv::OpBitcast;
3062 break;
3063
John Kessenich140f3df2015-06-26 16:58:36 -06003064 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003065 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003066 break;
3067 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003068 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003069 break;
3070 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003071 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003072 break;
3073 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003074 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003075 break;
3076 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003077 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003078 break;
3079 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003080 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003081 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003082 case glslang::EOpPackSnorm4x8:
3083 libCall = spv::GLSLstd450PackSnorm4x8;
3084 break;
3085 case glslang::EOpUnpackSnorm4x8:
3086 libCall = spv::GLSLstd450UnpackSnorm4x8;
3087 break;
3088 case glslang::EOpPackUnorm4x8:
3089 libCall = spv::GLSLstd450PackUnorm4x8;
3090 break;
3091 case glslang::EOpUnpackUnorm4x8:
3092 libCall = spv::GLSLstd450UnpackUnorm4x8;
3093 break;
3094 case glslang::EOpPackDouble2x32:
3095 libCall = spv::GLSLstd450PackDouble2x32;
3096 break;
3097 case glslang::EOpUnpackDouble2x32:
3098 libCall = spv::GLSLstd450UnpackDouble2x32;
3099 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003100
3101 case glslang::EOpDPdx:
3102 unaryOp = spv::OpDPdx;
3103 break;
3104 case glslang::EOpDPdy:
3105 unaryOp = spv::OpDPdy;
3106 break;
3107 case glslang::EOpFwidth:
3108 unaryOp = spv::OpFwidth;
3109 break;
3110 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003111 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003112 unaryOp = spv::OpDPdxFine;
3113 break;
3114 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003115 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003116 unaryOp = spv::OpDPdyFine;
3117 break;
3118 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003119 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003120 unaryOp = spv::OpFwidthFine;
3121 break;
3122 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003123 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003124 unaryOp = spv::OpDPdxCoarse;
3125 break;
3126 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003127 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003128 unaryOp = spv::OpDPdyCoarse;
3129 break;
3130 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003131 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003132 unaryOp = spv::OpFwidthCoarse;
3133 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003134 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003135 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003136 libCall = spv::GLSLstd450InterpolateAtCentroid;
3137 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003138 case glslang::EOpAny:
3139 unaryOp = spv::OpAny;
3140 break;
3141 case glslang::EOpAll:
3142 unaryOp = spv::OpAll;
3143 break;
3144
3145 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003146 if (isFloat)
3147 libCall = spv::GLSLstd450FAbs;
3148 else
3149 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003150 break;
3151 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003152 if (isFloat)
3153 libCall = spv::GLSLstd450FSign;
3154 else
3155 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003156 break;
3157
John Kessenichfc51d282015-08-19 13:34:18 -06003158 case glslang::EOpAtomicCounterIncrement:
3159 case glslang::EOpAtomicCounterDecrement:
3160 case glslang::EOpAtomicCounter:
3161 {
3162 // Handle all of the atomics in one place, in createAtomicOperation()
3163 std::vector<spv::Id> operands;
3164 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003165 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003166 }
3167
John Kessenichfc51d282015-08-19 13:34:18 -06003168 case glslang::EOpBitFieldReverse:
3169 unaryOp = spv::OpBitReverse;
3170 break;
3171 case glslang::EOpBitCount:
3172 unaryOp = spv::OpBitCount;
3173 break;
3174 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003175 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003176 break;
3177 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003178 if (isUnsigned)
3179 libCall = spv::GLSLstd450FindUMsb;
3180 else
3181 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003182 break;
3183
John Kessenich140f3df2015-06-26 16:58:36 -06003184 default:
3185 return 0;
3186 }
3187
3188 spv::Id id;
3189 if (libCall >= 0) {
3190 std::vector<spv::Id> args;
3191 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003192 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003193 } else
3194 id = builder.createUnaryOp(unaryOp, typeId, operand);
3195
John Kessenich32cfd492016-02-02 12:37:46 -07003196 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003197}
3198
John Kessenich7a53f762016-01-20 11:19:27 -07003199// Create a unary operation on a matrix
3200spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3201{
3202 // Handle unary operations vector by vector.
3203 // The result type is the same type as the original type.
3204 // The algorithm is to:
3205 // - break the matrix into vectors
3206 // - apply the operation to each vector
3207 // - make a matrix out the vector results
3208
3209 // get the types sorted out
3210 int numCols = builder.getNumColumns(operand);
3211 int numRows = builder.getNumRows(operand);
3212 spv::Id scalarType = builder.getScalarTypeId(typeId);
3213 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3214 std::vector<spv::Id> results;
3215
3216 // do each vector op
3217 for (int c = 0; c < numCols; ++c) {
3218 std::vector<unsigned int> indexes;
3219 indexes.push_back(c);
3220 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3221 results.push_back(builder.createUnaryOp(op, vecType, vec));
3222 builder.setPrecision(results.back(), precision);
3223 }
3224
3225 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003226 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003227}
3228
John Kessenich140f3df2015-06-26 16:58:36 -06003229spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3230{
3231 spv::Op convOp = spv::OpNop;
3232 spv::Id zero = 0;
3233 spv::Id one = 0;
3234
3235 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3236
3237 switch (op) {
3238 case glslang::EOpConvIntToBool:
3239 case glslang::EOpConvUintToBool:
3240 zero = builder.makeUintConstant(0);
3241 zero = makeSmearedConstant(zero, vectorSize);
3242 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3243
3244 case glslang::EOpConvFloatToBool:
3245 zero = builder.makeFloatConstant(0.0F);
3246 zero = makeSmearedConstant(zero, vectorSize);
3247 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3248
3249 case glslang::EOpConvDoubleToBool:
3250 zero = builder.makeDoubleConstant(0.0);
3251 zero = makeSmearedConstant(zero, vectorSize);
3252 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3253
3254 case glslang::EOpConvBoolToFloat:
3255 convOp = spv::OpSelect;
3256 zero = builder.makeFloatConstant(0.0);
3257 one = builder.makeFloatConstant(1.0);
3258 break;
3259 case glslang::EOpConvBoolToDouble:
3260 convOp = spv::OpSelect;
3261 zero = builder.makeDoubleConstant(0.0);
3262 one = builder.makeDoubleConstant(1.0);
3263 break;
3264 case glslang::EOpConvBoolToInt:
3265 zero = builder.makeIntConstant(0);
3266 one = builder.makeIntConstant(1);
3267 convOp = spv::OpSelect;
3268 break;
3269 case glslang::EOpConvBoolToUint:
3270 zero = builder.makeUintConstant(0);
3271 one = builder.makeUintConstant(1);
3272 convOp = spv::OpSelect;
3273 break;
3274
3275 case glslang::EOpConvIntToFloat:
3276 case glslang::EOpConvIntToDouble:
3277 convOp = spv::OpConvertSToF;
3278 break;
3279
3280 case glslang::EOpConvUintToFloat:
3281 case glslang::EOpConvUintToDouble:
3282 convOp = spv::OpConvertUToF;
3283 break;
3284
3285 case glslang::EOpConvDoubleToFloat:
3286 case glslang::EOpConvFloatToDouble:
3287 convOp = spv::OpFConvert;
3288 break;
3289
3290 case glslang::EOpConvFloatToInt:
3291 case glslang::EOpConvDoubleToInt:
3292 convOp = spv::OpConvertFToS;
3293 break;
3294
3295 case glslang::EOpConvUintToInt:
3296 case glslang::EOpConvIntToUint:
3297 convOp = spv::OpBitcast;
3298 break;
3299
3300 case glslang::EOpConvFloatToUint:
3301 case glslang::EOpConvDoubleToUint:
3302 convOp = spv::OpConvertFToU;
3303 break;
3304 default:
3305 break;
3306 }
3307
3308 spv::Id result = 0;
3309 if (convOp == spv::OpNop)
3310 return result;
3311
3312 if (convOp == spv::OpSelect) {
3313 zero = makeSmearedConstant(zero, vectorSize);
3314 one = makeSmearedConstant(one, vectorSize);
3315 result = builder.createTriOp(convOp, destType, operand, one, zero);
3316 } else
3317 result = builder.createUnaryOp(convOp, destType, operand);
3318
John Kessenich32cfd492016-02-02 12:37:46 -07003319 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003320}
3321
3322spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3323{
3324 if (vectorSize == 0)
3325 return constant;
3326
3327 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3328 std::vector<spv::Id> components;
3329 for (int c = 0; c < vectorSize; ++c)
3330 components.push_back(constant);
3331 return builder.makeCompositeConstant(vectorTypeId, components);
3332}
3333
John Kessenich426394d2015-07-23 10:22:48 -06003334// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003335spv::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 -06003336{
3337 spv::Op opCode = spv::OpNop;
3338
3339 switch (op) {
3340 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003341 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003342 opCode = spv::OpAtomicIAdd;
3343 break;
3344 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003345 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003346 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003347 break;
3348 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003349 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003350 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003351 break;
3352 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003353 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003354 opCode = spv::OpAtomicAnd;
3355 break;
3356 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003357 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003358 opCode = spv::OpAtomicOr;
3359 break;
3360 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003361 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003362 opCode = spv::OpAtomicXor;
3363 break;
3364 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003365 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003366 opCode = spv::OpAtomicExchange;
3367 break;
3368 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003369 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003370 opCode = spv::OpAtomicCompareExchange;
3371 break;
3372 case glslang::EOpAtomicCounterIncrement:
3373 opCode = spv::OpAtomicIIncrement;
3374 break;
3375 case glslang::EOpAtomicCounterDecrement:
3376 opCode = spv::OpAtomicIDecrement;
3377 break;
3378 case glslang::EOpAtomicCounter:
3379 opCode = spv::OpAtomicLoad;
3380 break;
3381 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003382 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003383 break;
3384 }
3385
3386 // Sort out the operands
3387 // - mapping from glslang -> SPV
3388 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003389 // - compare-exchange swaps the value and comparator
3390 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003391 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3392 auto opIt = operands.begin(); // walk the glslang operands
3393 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003394 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3395 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3396 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003397 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3398 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003399 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003400 spvAtomicOperands.push_back(*(opIt + 1));
3401 spvAtomicOperands.push_back(*opIt);
3402 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003403 }
John Kessenich426394d2015-07-23 10:22:48 -06003404
John Kessenich3e60a6f2015-09-14 22:45:16 -06003405 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003406 for (; opIt != operands.end(); ++opIt)
3407 spvAtomicOperands.push_back(*opIt);
3408
3409 return builder.createOp(opCode, typeId, spvAtomicOperands);
3410}
3411
John Kessenich5e4b1242015-08-06 22:53:06 -06003412spv::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 -06003413{
John Kessenich5e4b1242015-08-06 22:53:06 -06003414 bool isUnsigned = typeProxy == glslang::EbtUint;
3415 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3416
John Kessenich140f3df2015-06-26 16:58:36 -06003417 spv::Op opCode = spv::OpNop;
3418 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003419 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003420 spv::Id typeId0 = 0;
3421 if (consumedOperands > 0)
3422 typeId0 = builder.getTypeId(operands[0]);
3423 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003424
3425 switch (op) {
3426 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003427 if (isFloat)
3428 libCall = spv::GLSLstd450FMin;
3429 else if (isUnsigned)
3430 libCall = spv::GLSLstd450UMin;
3431 else
3432 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003433 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003434 break;
3435 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003436 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003437 break;
3438 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003439 if (isFloat)
3440 libCall = spv::GLSLstd450FMax;
3441 else if (isUnsigned)
3442 libCall = spv::GLSLstd450UMax;
3443 else
3444 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003445 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003446 break;
3447 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003448 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003449 break;
3450 case glslang::EOpDot:
3451 opCode = spv::OpDot;
3452 break;
3453 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003454 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003455 break;
3456
3457 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003458 if (isFloat)
3459 libCall = spv::GLSLstd450FClamp;
3460 else if (isUnsigned)
3461 libCall = spv::GLSLstd450UClamp;
3462 else
3463 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003464 builder.promoteScalar(precision, operands.front(), operands[1]);
3465 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003466 break;
3467 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003468 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3469 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003470 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003471 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003472 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003473 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003474 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003475 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003476 break;
3477 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003478 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003479 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003480 break;
3481 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003482 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003483 builder.promoteScalar(precision, operands[0], operands[2]);
3484 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003485 break;
3486
3487 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003488 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003489 break;
3490 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003491 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003492 break;
3493 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003494 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003495 break;
3496 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003497 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003498 break;
3499 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003500 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003501 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003502 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003503 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003504 libCall = spv::GLSLstd450InterpolateAtSample;
3505 break;
3506 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003507 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003508 libCall = spv::GLSLstd450InterpolateAtOffset;
3509 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003510 case glslang::EOpAddCarry:
3511 opCode = spv::OpIAddCarry;
3512 typeId = builder.makeStructResultType(typeId0, typeId0);
3513 consumedOperands = 2;
3514 break;
3515 case glslang::EOpSubBorrow:
3516 opCode = spv::OpISubBorrow;
3517 typeId = builder.makeStructResultType(typeId0, typeId0);
3518 consumedOperands = 2;
3519 break;
3520 case glslang::EOpUMulExtended:
3521 opCode = spv::OpUMulExtended;
3522 typeId = builder.makeStructResultType(typeId0, typeId0);
3523 consumedOperands = 2;
3524 break;
3525 case glslang::EOpIMulExtended:
3526 opCode = spv::OpSMulExtended;
3527 typeId = builder.makeStructResultType(typeId0, typeId0);
3528 consumedOperands = 2;
3529 break;
3530 case glslang::EOpBitfieldExtract:
3531 if (isUnsigned)
3532 opCode = spv::OpBitFieldUExtract;
3533 else
3534 opCode = spv::OpBitFieldSExtract;
3535 break;
3536 case glslang::EOpBitfieldInsert:
3537 opCode = spv::OpBitFieldInsert;
3538 break;
3539
3540 case glslang::EOpFma:
3541 libCall = spv::GLSLstd450Fma;
3542 break;
3543 case glslang::EOpFrexp:
3544 libCall = spv::GLSLstd450FrexpStruct;
3545 if (builder.getNumComponents(operands[0]) == 1)
3546 frexpIntType = builder.makeIntegerType(32, true);
3547 else
3548 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3549 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3550 consumedOperands = 1;
3551 break;
3552 case glslang::EOpLdexp:
3553 libCall = spv::GLSLstd450Ldexp;
3554 break;
3555
John Kessenich140f3df2015-06-26 16:58:36 -06003556 default:
3557 return 0;
3558 }
3559
3560 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003561 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003562 // Use an extended instruction from the standard library.
3563 // Construct the call arguments, without modifying the original operands vector.
3564 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3565 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003566 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003567 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003568 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003569 case 0:
3570 // should all be handled by visitAggregate and createNoArgOperation
3571 assert(0);
3572 return 0;
3573 case 1:
3574 // should all be handled by createUnaryOperation
3575 assert(0);
3576 return 0;
3577 case 2:
3578 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3579 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003580 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003581 // anything 3 or over doesn't have l-value operands, so all should be consumed
3582 assert(consumedOperands == operands.size());
3583 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003584 break;
3585 }
3586 }
3587
John Kessenich55e7d112015-11-15 21:33:39 -07003588 // Decode the return types that were structures
3589 switch (op) {
3590 case glslang::EOpAddCarry:
3591 case glslang::EOpSubBorrow:
3592 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3593 id = builder.createCompositeExtract(id, typeId0, 0);
3594 break;
3595 case glslang::EOpUMulExtended:
3596 case glslang::EOpIMulExtended:
3597 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3598 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3599 break;
3600 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003601 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003602 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3603 id = builder.createCompositeExtract(id, typeId0, 0);
3604 break;
3605 default:
3606 break;
3607 }
3608
John Kessenich32cfd492016-02-02 12:37:46 -07003609 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003610}
3611
3612// Intrinsics with no arguments, no return value, and no precision.
3613spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3614{
3615 // TODO: get the barrier operands correct
3616
3617 switch (op) {
3618 case glslang::EOpEmitVertex:
3619 builder.createNoResultOp(spv::OpEmitVertex);
3620 return 0;
3621 case glslang::EOpEndPrimitive:
3622 builder.createNoResultOp(spv::OpEndPrimitive);
3623 return 0;
3624 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003625 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3626 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003627 return 0;
3628 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003629 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003630 return 0;
3631 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003632 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003633 return 0;
3634 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003635 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003636 return 0;
3637 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003638 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003639 return 0;
3640 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003641 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003642 return 0;
3643 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003644 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003645 return 0;
3646 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003647 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003648 return 0;
3649 }
3650}
3651
3652spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3653{
John Kessenich2f273362015-07-18 22:34:27 -06003654 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003655 spv::Id id;
3656 if (symbolValues.end() != iter) {
3657 id = iter->second;
3658 return id;
3659 }
3660
3661 // it was not found, create it
3662 id = createSpvVariable(symbol);
3663 symbolValues[symbol->getId()] = id;
3664
3665 if (! symbol->getType().isStruct()) {
3666 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003667 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003668 if (symbol->getType().getQualifier().hasSpecConstantId())
3669 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003670 if (symbol->getQualifier().hasLocation())
3671 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3672 if (symbol->getQualifier().hasIndex())
3673 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3674 if (symbol->getQualifier().hasComponent())
3675 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3676 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003677 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003678 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003679 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003680 if (symbol->getQualifier().hasXfbBuffer())
3681 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3682 if (symbol->getQualifier().hasXfbOffset())
3683 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3684 }
3685 }
3686
John Kesseniche0b6cad2015-12-24 10:30:13 -07003687 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003688 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003689 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003690 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003691 }
John Kessenich140f3df2015-06-26 16:58:36 -06003692 if (symbol->getQualifier().hasSet())
3693 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003694 else if (IsDescriptorResource(symbol->getType())) {
3695 // default to 0
3696 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3697 }
John Kessenich140f3df2015-06-26 16:58:36 -06003698 if (symbol->getQualifier().hasBinding())
3699 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003700 if (symbol->getQualifier().hasAttachment())
3701 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003702 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003703 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003704 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003705 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003706 if (symbol->getQualifier().hasXfbBuffer())
3707 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3708 }
3709
Rex Xu1da878f2016-02-21 20:59:01 +08003710 if (symbol->getType().isImage()) {
3711 std::vector<spv::Decoration> memory;
3712 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3713 for (unsigned int i = 0; i < memory.size(); ++i)
3714 addDecoration(id, memory[i]);
3715 }
3716
John Kessenich140f3df2015-06-26 16:58:36 -06003717 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003718 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003719 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003720 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003721
John Kessenich140f3df2015-06-26 16:58:36 -06003722 return id;
3723}
3724
John Kessenich55e7d112015-11-15 21:33:39 -07003725// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003726void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3727{
3728 if (dec != spv::BadValue)
3729 builder.addDecoration(id, dec);
3730}
3731
John Kessenich55e7d112015-11-15 21:33:39 -07003732// If 'dec' is valid, add a one-operand decoration to an object
3733void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3734{
3735 if (dec != spv::BadValue)
3736 builder.addDecoration(id, dec, value);
3737}
3738
3739// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003740void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3741{
3742 if (dec != spv::BadValue)
3743 builder.addMemberDecoration(id, (unsigned)member, dec);
3744}
3745
John Kessenich92187592016-02-01 13:45:25 -07003746// If 'dec' is valid, add a one-operand decoration to a struct member
3747void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3748{
3749 if (dec != spv::BadValue)
3750 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3751}
3752
John Kessenich55e7d112015-11-15 21:33:39 -07003753// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003754// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003755//
3756// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3757//
3758// Recursively walk the nodes. The nodes form a tree whose leaves are
3759// regular constants, which themselves are trees that createSpvConstant()
3760// recursively walks. So, this function walks the "top" of the tree:
3761// - emit specialization constant-building instructions for specConstant
3762// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04003763spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07003764{
John Kessenich7cc0e282016-03-20 00:46:02 -06003765 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07003766
qining4f4bb812016-04-03 23:55:17 -04003767 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07003768 if (! node.getQualifier().specConstant) {
3769 // hand off to the non-spec-constant path
3770 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3771 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003772 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07003773 nextConst, false);
3774 }
3775
3776 // We now know we have a specialization constant to build
3777
qining4f4bb812016-04-03 23:55:17 -04003778 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3779 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3780 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3781 std::vector<spv::Id> dimConstId;
3782 for (int dim = 0; dim < 3; ++dim) {
3783 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3784 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3785 if (specConst)
3786 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3787 }
3788 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3789 }
3790
3791 // An AST node labelled as specialization constant should be a symbol node.
3792 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
3793 if (auto* sn = node.getAsSymbolNode()) {
3794 if (auto* sub_tree = sn->getConstSubtree()) {
3795 return createSpvConstantFromConstSubTree(sub_tree);
3796 } else if (auto* const_union_array = &sn->getConstArray()){
3797 int nextConst = 0;
3798 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07003799 }
3800 }
qining4f4bb812016-04-03 23:55:17 -04003801
3802 // Neither a front-end constant node, nor a specialization constant node with constant union array or
3803 // constant sub tree as initializer.
3804 spv::MissingFunctionality("Neither a front-end constant nor a spec constant.");
3805 exit(1);
3806 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07003807}
3808
John Kessenich140f3df2015-06-26 16:58:36 -06003809// Use 'consts' as the flattened glslang source of scalar constants to recursively
3810// build the aggregate SPIR-V constant.
3811//
3812// If there are not enough elements present in 'consts', 0 will be substituted;
3813// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3814//
qining08408382016-03-21 09:51:37 -04003815spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003816{
3817 // vector of constants for SPIR-V
3818 std::vector<spv::Id> spvConsts;
3819
3820 // Type is used for struct and array constants
3821 spv::Id typeId = convertGlslangToSpvType(glslangType);
3822
3823 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003824 glslang::TType elementType(glslangType, 0);
3825 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04003826 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003827 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003828 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003829 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04003830 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003831 } else if (glslangType.getStruct()) {
3832 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3833 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04003834 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003835 } else if (glslangType.isVector()) {
3836 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3837 bool zero = nextConst >= consts.size();
3838 switch (glslangType.getBasicType()) {
3839 case glslang::EbtInt:
3840 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3841 break;
3842 case glslang::EbtUint:
3843 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3844 break;
3845 case glslang::EbtFloat:
3846 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3847 break;
3848 case glslang::EbtDouble:
3849 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3850 break;
3851 case glslang::EbtBool:
3852 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3853 break;
3854 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003855 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003856 break;
3857 }
3858 ++nextConst;
3859 }
3860 } else {
3861 // we have a non-aggregate (scalar) constant
3862 bool zero = nextConst >= consts.size();
3863 spv::Id scalar = 0;
3864 switch (glslangType.getBasicType()) {
3865 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003866 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003867 break;
3868 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003869 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003870 break;
3871 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003872 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003873 break;
3874 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003875 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003876 break;
3877 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003878 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003879 break;
3880 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003881 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003882 break;
3883 }
3884 ++nextConst;
3885 return scalar;
3886 }
3887
3888 return builder.makeCompositeConstant(typeId, spvConsts);
3889}
3890
qining08408382016-03-21 09:51:37 -04003891// Create constant ID from const initializer sub tree.
3892spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstSubTree(
qining5c61d8e2016-03-31 13:57:28 -04003893 glslang::TIntermTyped* subTree)
3894{
qining08408382016-03-21 09:51:37 -04003895 const glslang::TType& glslangType = subTree->getType();
3896 spv::Id typeId = convertGlslangToSpvType(glslangType);
3897 bool is_spec_const = subTree->getType().getQualifier().isSpecConstant();
3898 if (const glslang::TIntermAggregate* an = subTree->getAsAggregate()) {
3899 // Aggregate node, we should generate OpConstantComposite or
3900 // OpSpecConstantComposite instruction.
qining13545202016-03-21 09:51:37 -04003901
qining08408382016-03-21 09:51:37 -04003902 std::vector<spv::Id> const_constituents;
3903 for (auto NI = an->getSequence().begin(); NI != an->getSequence().end();
3904 NI++) {
3905 const_constituents.push_back(
3906 createSpvConstantFromConstSubTree((*NI)->getAsTyped()));
3907 }
3908 // Note that constructors are aggregate nodes, so expressions like:
3909 // float x = float(y) will become an aggregate node. If 'x' is declared
3910 // as a constant, the aggregate node representing 'float(y)' will be
3911 // processed here.
3912 if (builder.isVectorType(typeId) || builder.isMatrixType(typeId) ||
3913 builder.isAggregateType(typeId)) {
3914 return builder.makeCompositeConstant(typeId, const_constituents, is_spec_const);
3915 } else {
3916 assert(builder.isScalarType(typeId) && const_constituents.size() == 1);
3917 return const_constituents.front();
3918 }
3919
qining13545202016-03-21 09:51:37 -04003920 } else if (glslang::TIntermBinary* bn = subTree->getAsBinaryNode()) {
qining08408382016-03-21 09:51:37 -04003921 // Binary operation node, we should generate OpSpecConstantOp <binary op>
3922 // This case should only happen when Specialization Constants are involved.
qining08408382016-03-21 09:51:37 -04003923
qining13545202016-03-21 09:51:37 -04003924 // Spec constants defined with binary operations and other constants requires
3925 // OpSpecConstantOp instruction.
qining5c61d8e2016-03-31 13:57:28 -04003926 SpecConstantOpModeGuard set_to_spec_const_mode(&builder);
qining13545202016-03-21 09:51:37 -04003927
3928 bn->traverse(this);
3929 return accessChainLoad(bn->getType());
3930
3931 } else if (glslang::TIntermUnary* un = subTree->getAsUnaryNode()) {
qining08408382016-03-21 09:51:37 -04003932 // Unary operation node, similar to binary operation node, should only
3933 // happen when specialization constants are involved.
qining13545202016-03-21 09:51:37 -04003934
3935 // Spec constants defined with unary operations and other constants requires
3936 // OpSpecConstantOp instruction.
qining5c61d8e2016-03-31 13:57:28 -04003937 SpecConstantOpModeGuard set_to_spec_const_mode(&builder);
qining13545202016-03-21 09:51:37 -04003938
3939 un->traverse(this);
3940 return accessChainLoad(un->getType());
qining08408382016-03-21 09:51:37 -04003941
3942 } else if (const glslang::TIntermConstantUnion* cn = subTree->getAsConstantUnion()) {
3943 // ConstantUnion node, should redirect to
3944 // createSpvConstantFromConstUnionArray
3945 int nextConst = 0;
3946 return createSpvConstantFromConstUnionArray(
3947 glslangType, cn->getConstArray(), nextConst, is_spec_const);
3948
3949 } else if (const glslang::TIntermSymbol* sn = subTree->getAsSymbolNode()) {
3950 // Symbol node. Call getSymbolId(). This should cover both cases 1) the
3951 // symbol has already been assigned an ID, 2) need a new ID for this
3952 // symbol.
3953 return getSymbolId(sn);
3954
3955 } else {
3956 spv::MissingFunctionality(
3957 "createSpvConstantFromConstSubTree() not covered TIntermTyped* const "
3958 "initializer subtree.");
3959 return spv::NoResult;
3960 }
3961}
3962
John Kessenich7c1aa102015-10-15 13:29:11 -06003963// Return true if the node is a constant or symbol whose reading has no
3964// non-trivial observable cost or effect.
3965bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3966{
3967 // don't know what this is
3968 if (node == nullptr)
3969 return false;
3970
3971 // a constant is safe
3972 if (node->getAsConstantUnion() != nullptr)
3973 return true;
3974
3975 // not a symbol means non-trivial
3976 if (node->getAsSymbolNode() == nullptr)
3977 return false;
3978
3979 // a symbol, depends on what's being read
3980 switch (node->getType().getQualifier().storage) {
3981 case glslang::EvqTemporary:
3982 case glslang::EvqGlobal:
3983 case glslang::EvqIn:
3984 case glslang::EvqInOut:
3985 case glslang::EvqConst:
3986 case glslang::EvqConstReadOnly:
3987 case glslang::EvqUniform:
3988 return true;
3989 default:
3990 return false;
3991 }
3992}
3993
3994// A node is trivial if it is a single operation with no side effects.
3995// Error on the side of saying non-trivial.
3996// Return true if trivial.
3997bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3998{
3999 if (node == nullptr)
4000 return false;
4001
4002 // symbols and constants are trivial
4003 if (isTrivialLeaf(node))
4004 return true;
4005
4006 // otherwise, it needs to be a simple operation or one or two leaf nodes
4007
4008 // not a simple operation
4009 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4010 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4011 if (binaryNode == nullptr && unaryNode == nullptr)
4012 return false;
4013
4014 // not on leaf nodes
4015 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4016 return false;
4017
4018 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4019 return false;
4020 }
4021
4022 switch (node->getAsOperator()->getOp()) {
4023 case glslang::EOpLogicalNot:
4024 case glslang::EOpConvIntToBool:
4025 case glslang::EOpConvUintToBool:
4026 case glslang::EOpConvFloatToBool:
4027 case glslang::EOpConvDoubleToBool:
4028 case glslang::EOpEqual:
4029 case glslang::EOpNotEqual:
4030 case glslang::EOpLessThan:
4031 case glslang::EOpGreaterThan:
4032 case glslang::EOpLessThanEqual:
4033 case glslang::EOpGreaterThanEqual:
4034 case glslang::EOpIndexDirect:
4035 case glslang::EOpIndexDirectStruct:
4036 case glslang::EOpLogicalXor:
4037 case glslang::EOpAny:
4038 case glslang::EOpAll:
4039 return true;
4040 default:
4041 return false;
4042 }
4043}
4044
4045// Emit short-circuiting code, where 'right' is never evaluated unless
4046// the left side is true (for &&) or false (for ||).
4047spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4048{
4049 spv::Id boolTypeId = builder.makeBoolType();
4050
4051 // emit left operand
4052 builder.clearAccessChain();
4053 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004054 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004055
4056 // Operands to accumulate OpPhi operands
4057 std::vector<spv::Id> phiOperands;
4058 // accumulate left operand's phi information
4059 phiOperands.push_back(leftId);
4060 phiOperands.push_back(builder.getBuildPoint()->getId());
4061
4062 // Make the two kinds of operation symmetric with a "!"
4063 // || => emit "if (! left) result = right"
4064 // && => emit "if ( left) result = right"
4065 //
4066 // TODO: this runtime "not" for || could be avoided by adding functionality
4067 // to 'builder' to have an "else" without an "then"
4068 if (op == glslang::EOpLogicalOr)
4069 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4070
4071 // make an "if" based on the left value
4072 spv::Builder::If ifBuilder(leftId, builder);
4073
4074 // emit right operand as the "then" part of the "if"
4075 builder.clearAccessChain();
4076 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004077 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004078
4079 // accumulate left operand's phi information
4080 phiOperands.push_back(rightId);
4081 phiOperands.push_back(builder.getBuildPoint()->getId());
4082
4083 // finish the "if"
4084 ifBuilder.makeEndIf();
4085
4086 // phi together the two results
4087 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4088}
4089
John Kessenich140f3df2015-06-26 16:58:36 -06004090}; // end anonymous namespace
4091
4092namespace glslang {
4093
John Kessenich68d78fd2015-07-12 19:28:10 -06004094void GetSpirvVersion(std::string& version)
4095{
John Kessenich9e55f632015-07-15 10:03:39 -06004096 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004097 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004098 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004099 version = buf;
4100}
4101
John Kessenich140f3df2015-06-26 16:58:36 -06004102// Write SPIR-V out to a binary file
4103void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4104{
4105 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004106 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004107 for (int i = 0; i < (int)spirv.size(); ++i) {
4108 unsigned int word = spirv[i];
4109 out.write((const char*)&word, 4);
4110 }
4111 out.close();
4112}
4113
4114//
4115// Set up the glslang traversal
4116//
4117void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4118{
4119 TIntermNode* root = intermediate.getTreeRoot();
4120
4121 if (root == 0)
4122 return;
4123
4124 glslang::GetThreadPoolAllocator().push();
4125
4126 TGlslangToSpvTraverser it(&intermediate);
4127
4128 root->traverse(&it);
4129
4130 it.dumpSpv(spirv);
4131
4132 glslang::GetThreadPoolAllocator().pop();
4133}
4134
4135}; // end namespace glslang