blob: 1a8ba44982c5ea4e14b385f4240cbcb9c27ffea4 [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
69//
70// The main holder of information for translating glslang to SPIR-V.
71//
72// Derives from the AST walking base class.
73//
74class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
75public:
76 TGlslangToSpvTraverser(const glslang::TIntermediate*);
77 virtual ~TGlslangToSpvTraverser();
78
79 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
80 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
81 void visitConstantUnion(glslang::TIntermConstantUnion*);
82 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
83 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
84 void visitSymbol(glslang::TIntermSymbol* symbol);
85 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
86 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
87 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
88
John Kessenich7ba63412015-12-20 17:37:07 -070089 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -060090
91protected:
John Kessenich5e801132016-02-15 11:09:46 -070092 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
John Kessenich92187592016-02-01 13:45:25 -070093 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable);
John Kessenich5d0fa972016-02-15 11:57:00 -070094 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -060095 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
96 spv::Id getSampledType(const glslang::TSampler&);
97 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -070098 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6c292d32016-02-15 20:58:50 -070099 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700100 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800101 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700102 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700103 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
104 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
105 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 -0600106
107 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
108 void makeFunctions(const glslang::TIntermSequence&);
109 void makeGlobalInitializers(const glslang::TIntermSequence&);
110 void visitFunctions(const glslang::TIntermSequence&);
111 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800112 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600113 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
114 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600115 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
116
117 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 -0700118 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800119 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 -0700120 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600121 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
122 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800123 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 -0600124 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 -0600125 spv::Id createNoArgOperation(glslang::TOperator op);
126 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
127 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700128 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600129 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700130 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
John Kessenich55e7d112015-11-15 21:33:39 -0700131 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
132 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600133 bool isTrivialLeaf(const glslang::TIntermTyped* node);
134 bool isTrivial(const glslang::TIntermTyped* node);
135 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600136
137 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700138 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600139 int sequenceDepth;
140
141 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
142 spv::Builder builder;
143 bool inMain;
144 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700145 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 -0700146 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600147 const glslang::TIntermediate* glslangIntermediate;
148 spv::Id stdBuiltins;
149
John Kessenich2f273362015-07-18 22:34:27 -0600150 std::unordered_map<int, spv::Id> symbolValues;
151 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
152 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700153 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600154 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 -0600155 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600156};
157
158//
159// Helper functions for translating glslang representations to SPIR-V enumerants.
160//
161
162// Translate glslang profile to SPIR-V source language.
163spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
164{
165 switch (profile) {
166 case ENoProfile:
167 case ECoreProfile:
168 case ECompatibilityProfile:
169 return spv::SourceLanguageGLSL;
170 case EEsProfile:
171 return spv::SourceLanguageESSL;
172 default:
173 return spv::SourceLanguageUnknown;
174 }
175}
176
177// Translate glslang language (stage) to SPIR-V execution model.
178spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
179{
180 switch (stage) {
181 case EShLangVertex: return spv::ExecutionModelVertex;
182 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
183 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
184 case EShLangGeometry: return spv::ExecutionModelGeometry;
185 case EShLangFragment: return spv::ExecutionModelFragment;
186 case EShLangCompute: return spv::ExecutionModelGLCompute;
187 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700188 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600189 return spv::ExecutionModelFragment;
190 }
191}
192
193// Translate glslang type to SPIR-V storage class.
194spv::StorageClass TranslateStorageClass(const glslang::TType& type)
195{
196 if (type.getQualifier().isPipeInput())
197 return spv::StorageClassInput;
198 else if (type.getQualifier().isPipeOutput())
199 return spv::StorageClassOutput;
200 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700201 if (type.getQualifier().layoutPushConstant)
202 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600203 if (type.getBasicType() == glslang::EbtBlock)
204 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800205 else if (type.getBasicType() == glslang::EbtAtomicUint)
206 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600207 else
208 return spv::StorageClassUniformConstant;
209 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
210 } else {
211 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700212 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
213 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600214 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
215 case glslang::EvqTemporary: return spv::StorageClassFunction;
216 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700217 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600218 return spv::StorageClassFunction;
219 }
220 }
221}
222
223// Translate glslang sampler type to SPIR-V dimensionality.
224spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
225{
226 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700227 case glslang::Esd1D: return spv::Dim1D;
228 case glslang::Esd2D: return spv::Dim2D;
229 case glslang::Esd3D: return spv::Dim3D;
230 case glslang::EsdCube: return spv::DimCube;
231 case glslang::EsdRect: return spv::DimRect;
232 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700233 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600234 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700235 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600236 return spv::Dim2D;
237 }
238}
239
240// Translate glslang type to SPIR-V precision decorations.
241spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
242{
243 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700244 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600245 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600246 default:
247 return spv::NoPrecision;
248 }
249}
250
251// Translate glslang type to SPIR-V block decorations.
252spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
253{
254 if (type.getBasicType() == glslang::EbtBlock) {
255 switch (type.getQualifier().storage) {
256 case glslang::EvqUniform: return spv::DecorationBlock;
257 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
258 case glslang::EvqVaryingIn: return spv::DecorationBlock;
259 case glslang::EvqVaryingOut: return spv::DecorationBlock;
260 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700261 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600262 break;
263 }
264 }
265
266 return (spv::Decoration)spv::BadValue;
267}
268
Rex Xu1da878f2016-02-21 20:59:01 +0800269// Translate glslang type to SPIR-V memory decorations.
270void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
271{
272 if (qualifier.coherent)
273 memory.push_back(spv::DecorationCoherent);
274 if (qualifier.volatil)
275 memory.push_back(spv::DecorationVolatile);
276 if (qualifier.restrict)
277 memory.push_back(spv::DecorationRestrict);
278 if (qualifier.readonly)
279 memory.push_back(spv::DecorationNonWritable);
280 if (qualifier.writeonly)
281 memory.push_back(spv::DecorationNonReadable);
282}
283
John Kessenich140f3df2015-06-26 16:58:36 -0600284// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700285spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600286{
287 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700288 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600289 case glslang::ElmRowMajor:
290 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700291 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600292 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700293 default:
294 // opaque layouts don't need a majorness
295 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600296 }
297 } else {
298 switch (type.getBasicType()) {
299 default:
300 return (spv::Decoration)spv::BadValue;
301 break;
302 case glslang::EbtBlock:
303 switch (type.getQualifier().storage) {
304 case glslang::EvqUniform:
305 case glslang::EvqBuffer:
306 switch (type.getQualifier().layoutPacking) {
307 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600308 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
309 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600310 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600311 }
312 case glslang::EvqVaryingIn:
313 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700314 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600315 return (spv::Decoration)spv::BadValue;
316 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700317 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600318 return (spv::Decoration)spv::BadValue;
319 }
320 }
321 }
322}
323
324// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700325// Returns spv::Decoration(spv::BadValue) when no decoration
326// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700327spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600328{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700329 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700330 // Smooth decoration doesn't exist in SPIR-V 1.0
331 return (spv::Decoration)spv::BadValue;
332 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700333 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700334 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700335 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600336 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700337 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600338 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700339 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600340 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700341 else if (qualifier.sample) {
342 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600343 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700344 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600345 return (spv::Decoration)spv::BadValue;
346}
347
John Kessenich92187592016-02-01 13:45:25 -0700348// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700349spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600350{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700351 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600352 return spv::DecorationInvariant;
353 else
354 return (spv::Decoration)spv::BadValue;
355}
356
357// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700358spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600359{
360 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700361 case glslang::EbvPointSize:
362 switch (glslangIntermediate->getStage()) {
363 case EShLangGeometry:
364 builder.addCapability(spv::CapabilityGeometryPointSize);
365 break;
366 case EShLangTessControl:
367 case EShLangTessEvaluation:
368 builder.addCapability(spv::CapabilityTessellationPointSize);
369 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100370 default:
371 break;
John Kessenich92187592016-02-01 13:45:25 -0700372 }
373 return spv::BuiltInPointSize;
374
375 case glslang::EbvClipDistance:
376 builder.addCapability(spv::CapabilityClipDistance);
377 return spv::BuiltInClipDistance;
378
379 case glslang::EbvCullDistance:
380 builder.addCapability(spv::CapabilityCullDistance);
381 return spv::BuiltInCullDistance;
382
383 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500384 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700385 return spv::BuiltInViewportIndex;
386
John Kessenich5e801132016-02-15 11:09:46 -0700387 case glslang::EbvSampleId:
388 builder.addCapability(spv::CapabilitySampleRateShading);
389 return spv::BuiltInSampleId;
390
391 case glslang::EbvSamplePosition:
392 builder.addCapability(spv::CapabilitySampleRateShading);
393 return spv::BuiltInSamplePosition;
394
395 case glslang::EbvSampleMask:
396 builder.addCapability(spv::CapabilitySampleRateShading);
397 return spv::BuiltInSampleMask;
398
John Kessenich140f3df2015-06-26 16:58:36 -0600399 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600400 case glslang::EbvVertexId: return spv::BuiltInVertexId;
401 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700402 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
403 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600404 case glslang::EbvBaseVertex:
405 case glslang::EbvBaseInstance:
406 case glslang::EbvDrawId:
407 // TODO: Add SPIR-V builtin ID.
408 spv::MissingFunctionality("Draw parameters");
409 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600410 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
411 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
412 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600413 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
414 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
415 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
416 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
417 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
418 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
419 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600420 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
421 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
422 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
423 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
424 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
425 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
426 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
427 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
428 default: return (spv::BuiltIn)spv::BadValue;
429 }
430}
431
Rex Xufc618912015-09-09 16:42:49 +0800432// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700433spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800434{
435 assert(type.getBasicType() == glslang::EbtSampler);
436
John Kessenich5d0fa972016-02-15 11:57:00 -0700437 // Check for capabilities
438 switch (type.getQualifier().layoutFormat) {
439 case glslang::ElfRg32f:
440 case glslang::ElfRg16f:
441 case glslang::ElfR11fG11fB10f:
442 case glslang::ElfR16f:
443 case glslang::ElfRgba16:
444 case glslang::ElfRgb10A2:
445 case glslang::ElfRg16:
446 case glslang::ElfRg8:
447 case glslang::ElfR16:
448 case glslang::ElfR8:
449 case glslang::ElfRgba16Snorm:
450 case glslang::ElfRg16Snorm:
451 case glslang::ElfRg8Snorm:
452 case glslang::ElfR16Snorm:
453 case glslang::ElfR8Snorm:
454
455 case glslang::ElfRg32i:
456 case glslang::ElfRg16i:
457 case glslang::ElfRg8i:
458 case glslang::ElfR16i:
459 case glslang::ElfR8i:
460
461 case glslang::ElfRgb10a2ui:
462 case glslang::ElfRg32ui:
463 case glslang::ElfRg16ui:
464 case glslang::ElfRg8ui:
465 case glslang::ElfR16ui:
466 case glslang::ElfR8ui:
467 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
468 break;
469
470 default:
471 break;
472 }
473
474 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800475 switch (type.getQualifier().layoutFormat) {
476 case glslang::ElfNone: return spv::ImageFormatUnknown;
477 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
478 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
479 case glslang::ElfR32f: return spv::ImageFormatR32f;
480 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
481 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
482 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
483 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
484 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
485 case glslang::ElfR16f: return spv::ImageFormatR16f;
486 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
487 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
488 case glslang::ElfRg16: return spv::ImageFormatRg16;
489 case glslang::ElfRg8: return spv::ImageFormatRg8;
490 case glslang::ElfR16: return spv::ImageFormatR16;
491 case glslang::ElfR8: return spv::ImageFormatR8;
492 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
493 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
494 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
495 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
496 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
497 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
498 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
499 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
500 case glslang::ElfR32i: return spv::ImageFormatR32i;
501 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
502 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
503 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
504 case glslang::ElfR16i: return spv::ImageFormatR16i;
505 case glslang::ElfR8i: return spv::ImageFormatR8i;
506 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
507 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
508 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
509 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
510 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
511 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
512 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
513 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
514 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
515 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
516 default: return (spv::ImageFormat)spv::BadValue;
517 }
518}
519
John Kessenich6c292d32016-02-15 20:58:50 -0700520// Return whether or not the given type is something that should be tied to a
521// descriptor set.
522bool IsDescriptorResource(const glslang::TType& type)
523{
John Kessenichf7497e22016-03-08 21:36:22 -0700524 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700525 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700526 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700527
528 // non block...
529 // basically samplerXXX/subpass/sampler/texture are all included
530 // if they are the global-scope-class, not the function parameter
531 // (or local, if they ever exist) class.
532 if (type.getBasicType() == glslang::EbtSampler)
533 return type.getQualifier().isUniformOrBuffer();
534
535 // None of the above.
536 return false;
537}
538
John Kesseniche0b6cad2015-12-24 10:30:13 -0700539void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
540{
541 if (child.layoutMatrix == glslang::ElmNone)
542 child.layoutMatrix = parent.layoutMatrix;
543
544 if (parent.invariant)
545 child.invariant = true;
546 if (parent.nopersp)
547 child.nopersp = true;
548 if (parent.flat)
549 child.flat = true;
550 if (parent.centroid)
551 child.centroid = true;
552 if (parent.patch)
553 child.patch = true;
554 if (parent.sample)
555 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800556 if (parent.coherent)
557 child.coherent = true;
558 if (parent.volatil)
559 child.volatil = true;
560 if (parent.restrict)
561 child.restrict = true;
562 if (parent.readonly)
563 child.readonly = true;
564 if (parent.writeonly)
565 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700566}
567
568bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
569{
John Kessenich7b9fa252016-01-21 18:56:57 -0700570 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700571 // - struct members can inherit from a struct declaration
572 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
573 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700574 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700575}
576
John Kessenich140f3df2015-06-26 16:58:36 -0600577//
578// Implement the TGlslangToSpvTraverser class.
579//
580
581TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
582 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700583 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600584 inMain(false), mainTerminated(false), linkageOnly(false),
585 glslangIntermediate(glslangIntermediate)
586{
587 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
588
589 builder.clearAccessChain();
590 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
591 stdBuiltins = builder.import("GLSL.std.450");
592 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
593 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700594 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600595
596 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600597 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
598 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600599 builder.addSourceExtension(it->c_str());
600
601 // Add the top-level modes for this shader.
602
John Kessenich92187592016-02-01 13:45:25 -0700603 if (glslangIntermediate->getXfbMode()) {
604 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600605 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700606 }
John Kessenich140f3df2015-06-26 16:58:36 -0600607
608 unsigned int mode;
609 switch (glslangIntermediate->getStage()) {
610 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600611 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600612 break;
613
614 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600615 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600616 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
617 break;
618
619 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600620 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600621 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700622 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
623 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
624 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600625 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600626 }
627 if (mode != spv::BadValue)
628 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
629
John Kesseniche6903322015-10-13 16:29:02 -0600630 switch (glslangIntermediate->getVertexSpacing()) {
631 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
632 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
633 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
634 default: mode = spv::BadValue; break;
635 }
636 if (mode != spv::BadValue)
637 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
638
639 switch (glslangIntermediate->getVertexOrder()) {
640 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
641 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
642 default: mode = spv::BadValue; break;
643 }
644 if (mode != spv::BadValue)
645 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
646
647 if (glslangIntermediate->getPointMode())
648 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600649 break;
650
651 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600652 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600653 switch (glslangIntermediate->getInputPrimitive()) {
654 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
655 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
656 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700657 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600658 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
659 default: mode = spv::BadValue; break;
660 }
661 if (mode != spv::BadValue)
662 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600663
John Kessenich140f3df2015-06-26 16:58:36 -0600664 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
665
666 switch (glslangIntermediate->getOutputPrimitive()) {
667 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
668 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
669 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
670 default: mode = spv::BadValue; break;
671 }
672 if (mode != spv::BadValue)
673 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
674 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
675 break;
676
677 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600678 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600679 if (glslangIntermediate->getPixelCenterInteger())
680 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600681
John Kessenich140f3df2015-06-26 16:58:36 -0600682 if (glslangIntermediate->getOriginUpperLeft())
683 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600684 else
685 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600686
687 if (glslangIntermediate->getEarlyFragmentTests())
688 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
689
690 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600691 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
692 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
693 default: mode = spv::BadValue; break;
694 }
695 if (mode != spv::BadValue)
696 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
697
698 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
699 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600700 break;
701
702 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600703 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600704 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
705 glslangIntermediate->getLocalSize(1),
706 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600707 break;
708
709 default:
710 break;
711 }
712
713}
714
John Kessenich7ba63412015-12-20 17:37:07 -0700715// Finish everything and dump
716void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
717{
718 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100719 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
720 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700721
722 builder.dump(out);
723}
724
John Kessenich140f3df2015-06-26 16:58:36 -0600725TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
726{
727 if (! mainTerminated) {
728 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
729 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600730 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600731 }
732}
733
734//
735// Implement the traversal functions.
736//
737// Return true from interior nodes to have the external traversal
738// continue on to children. Return false if children were
739// already processed.
740//
741
742//
743// Symbols can turn into
744// - uniform/input reads
745// - output writes
746// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
747// - something simple that degenerates into the last bullet
748//
749void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
750{
751 // getSymbolId() will set up all the IO decorations on the first call.
752 // Formal function parameters were mapped during makeFunctions().
753 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700754
755 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
756 if (builder.isPointer(id)) {
757 spv::StorageClass sc = builder.getStorageClass(id);
758 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
759 iOSet.insert(id);
760 }
761
762 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700763 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600764 // Prepare to generate code for the access
765
766 // L-value chains will be computed left to right. We're on the symbol now,
767 // which is the left-most part of the access chain, so now is "clear" time,
768 // followed by setting the base.
769 builder.clearAccessChain();
770
771 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700772 // except for
773 // A) "const in" arguments to a function, which are an intermediate object.
774 // See comments in handleUserFunctionCall().
775 // B) Specialization constants (normal constant don't even come in as a variable),
776 // These are also pure R-values.
777 glslang::TQualifier qualifier = symbol->getQualifier();
778 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
779 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600780 builder.setAccessChainRValue(id);
781 else
782 builder.setAccessChainLValue(id);
783 }
784}
785
786bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
787{
788 // First, handle special cases
789 switch (node->getOp()) {
790 case glslang::EOpAssign:
791 case glslang::EOpAddAssign:
792 case glslang::EOpSubAssign:
793 case glslang::EOpMulAssign:
794 case glslang::EOpVectorTimesMatrixAssign:
795 case glslang::EOpVectorTimesScalarAssign:
796 case glslang::EOpMatrixTimesScalarAssign:
797 case glslang::EOpMatrixTimesMatrixAssign:
798 case glslang::EOpDivAssign:
799 case glslang::EOpModAssign:
800 case glslang::EOpAndAssign:
801 case glslang::EOpInclusiveOrAssign:
802 case glslang::EOpExclusiveOrAssign:
803 case glslang::EOpLeftShiftAssign:
804 case glslang::EOpRightShiftAssign:
805 // A bin-op assign "a += b" means the same thing as "a = a + b"
806 // where a is evaluated before b. For a simple assignment, GLSL
807 // says to evaluate the left before the right. So, always, left
808 // node then right node.
809 {
810 // get the left l-value, save it away
811 builder.clearAccessChain();
812 node->getLeft()->traverse(this);
813 spv::Builder::AccessChain lValue = builder.getAccessChain();
814
815 // evaluate the right
816 builder.clearAccessChain();
817 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700818 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600819
820 if (node->getOp() != glslang::EOpAssign) {
821 // the left is also an r-value
822 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700823 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600824
825 // do the operation
826 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
827 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
828 node->getType().getBasicType());
829
830 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700831 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600832 }
833
834 // store the result
835 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800836 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600837
838 // assignments are expressions having an rValue after they are evaluated...
839 builder.clearAccessChain();
840 builder.setAccessChainRValue(rValue);
841 }
842 return false;
843 case glslang::EOpIndexDirect:
844 case glslang::EOpIndexDirectStruct:
845 {
846 // Get the left part of the access chain.
847 node->getLeft()->traverse(this);
848
849 // Add the next element in the chain
850
John Kessenich55e7d112015-11-15 21:33:39 -0700851 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600852 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
853 // This may be, e.g., an anonymous block-member selection, which generally need
854 // index remapping due to hidden members in anonymous blocks.
855 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700856 assert(remapper.size() > 0);
857 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600858 }
859
860 if (! node->getLeft()->getType().isArray() &&
861 node->getLeft()->getType().isVector() &&
862 node->getOp() == glslang::EOpIndexDirect) {
863 // This is essentially a hard-coded vector swizzle of size 1,
864 // so short circuit the access-chain stuff with a swizzle.
865 std::vector<unsigned> swizzle;
866 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600867 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600868 } else {
869 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600870 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600871 }
872 }
873 return false;
874 case glslang::EOpIndexIndirect:
875 {
876 // Structure or array or vector indirection.
877 // Will use native SPIR-V access-chain for struct and array indirection;
878 // matrices are arrays of vectors, so will also work for a matrix.
879 // Will use the access chain's 'component' for variable index into a vector.
880
881 // This adapter is building access chains left to right.
882 // Set up the access chain to the left.
883 node->getLeft()->traverse(this);
884
885 // save it so that computing the right side doesn't trash it
886 spv::Builder::AccessChain partial = builder.getAccessChain();
887
888 // compute the next index in the chain
889 builder.clearAccessChain();
890 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700891 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600892
893 // restore the saved access chain
894 builder.setAccessChain(partial);
895
896 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600897 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600898 else
John Kessenichfa668da2015-09-13 14:46:30 -0600899 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600900 }
901 return false;
902 case glslang::EOpVectorSwizzle:
903 {
904 node->getLeft()->traverse(this);
905 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
906 std::vector<unsigned> swizzle;
907 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
908 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600909 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600910 }
911 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600912 case glslang::EOpLogicalOr:
913 case glslang::EOpLogicalAnd:
914 {
915
916 // These may require short circuiting, but can sometimes be done as straight
917 // binary operations. The right operand must be short circuited if it has
918 // side effects, and should probably be if it is complex.
919 if (isTrivial(node->getRight()->getAsTyped()))
920 break; // handle below as a normal binary operation
921 // otherwise, we need to do dynamic short circuiting on the right operand
922 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
923 builder.clearAccessChain();
924 builder.setAccessChainRValue(result);
925 }
926 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600927 default:
928 break;
929 }
930
931 // Assume generic binary op...
932
John Kessenich32cfd492016-02-02 12:37:46 -0700933 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600934 builder.clearAccessChain();
935 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700936 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600937
John Kessenich32cfd492016-02-02 12:37:46 -0700938 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600939 builder.clearAccessChain();
940 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700941 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600942
John Kessenich32cfd492016-02-02 12:37:46 -0700943 // get result
944 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
945 convertGlslangToSpvType(node->getType()), left, right,
946 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600947
John Kessenich50e57562015-12-21 21:21:11 -0700948 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600949 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700950 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700951 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600952 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600953 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600954 return false;
955 }
John Kessenich140f3df2015-06-26 16:58:36 -0600956}
957
958bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
959{
John Kessenichfc51d282015-08-19 13:34:18 -0600960 spv::Id result = spv::NoResult;
961
962 // try texturing first
963 result = createImageTextureFunctionCall(node);
964 if (result != spv::NoResult) {
965 builder.clearAccessChain();
966 builder.setAccessChainRValue(result);
967
968 return false; // done with this node
969 }
970
971 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600972
973 if (node->getOp() == glslang::EOpArrayLength) {
974 // Quite special; won't want to evaluate the operand.
975
976 // Normal .length() would have been constant folded by the front-end.
977 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600978 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600979 assert(node->getOperand()->getType().isRuntimeSizedArray());
980 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
981 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600982 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
983 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600984
985 builder.clearAccessChain();
986 builder.setAccessChainRValue(length);
987
988 return false;
989 }
990
John Kessenichfc51d282015-08-19 13:34:18 -0600991 // Start by evaluating the operand
992
John Kessenich140f3df2015-06-26 16:58:36 -0600993 builder.clearAccessChain();
994 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800995
Rex Xufc618912015-09-09 16:42:49 +0800996 spv::Id operand = spv::NoResult;
997
998 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
999 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001000 node->getOp() == glslang::EOpAtomicCounter ||
1001 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001002 operand = builder.accessChainGetLValue(); // Special case l-value operands
1003 else
John Kessenich32cfd492016-02-02 12:37:46 -07001004 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001005
1006 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1007
1008 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001009 if (! result)
1010 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -06001011
1012 // if not, then possibly an operation
1013 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -07001014 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001015
1016 if (result) {
1017 builder.clearAccessChain();
1018 builder.setAccessChainRValue(result);
1019
1020 return false; // done with this node
1021 }
1022
1023 // it must be a special case, check...
1024 switch (node->getOp()) {
1025 case glslang::EOpPostIncrement:
1026 case glslang::EOpPostDecrement:
1027 case glslang::EOpPreIncrement:
1028 case glslang::EOpPreDecrement:
1029 {
1030 // we need the integer value "1" or the floating point "1.0" to add/subtract
1031 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
1032 builder.makeFloatConstant(1.0F) :
1033 builder.makeIntConstant(1);
1034 glslang::TOperator op;
1035 if (node->getOp() == glslang::EOpPreIncrement ||
1036 node->getOp() == glslang::EOpPostIncrement)
1037 op = glslang::EOpAdd;
1038 else
1039 op = glslang::EOpSub;
1040
1041 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1042 convertGlslangToSpvType(node->getType()), operand, one,
1043 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001044 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001045
1046 // The result of operation is always stored, but conditionally the
1047 // consumed result. The consumed result is always an r-value.
1048 builder.accessChainStore(result);
1049 builder.clearAccessChain();
1050 if (node->getOp() == glslang::EOpPreIncrement ||
1051 node->getOp() == glslang::EOpPreDecrement)
1052 builder.setAccessChainRValue(result);
1053 else
1054 builder.setAccessChainRValue(operand);
1055 }
1056
1057 return false;
1058
1059 case glslang::EOpEmitStreamVertex:
1060 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1061 return false;
1062 case glslang::EOpEndStreamPrimitive:
1063 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1064 return false;
1065
1066 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001067 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001068 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001069 }
John Kessenich140f3df2015-06-26 16:58:36 -06001070}
1071
1072bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1073{
John Kessenichfc51d282015-08-19 13:34:18 -06001074 spv::Id result = spv::NoResult;
1075
1076 // try texturing
1077 result = createImageTextureFunctionCall(node);
1078 if (result != spv::NoResult) {
1079 builder.clearAccessChain();
1080 builder.setAccessChainRValue(result);
1081
1082 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001083 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001084 // "imageStore" is a special case, which has no result
1085 return false;
1086 }
John Kessenichfc51d282015-08-19 13:34:18 -06001087
John Kessenich140f3df2015-06-26 16:58:36 -06001088 glslang::TOperator binOp = glslang::EOpNull;
1089 bool reduceComparison = true;
1090 bool isMatrix = false;
1091 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001092 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001093
1094 assert(node->getOp());
1095
1096 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1097
1098 switch (node->getOp()) {
1099 case glslang::EOpSequence:
1100 {
1101 if (preVisit)
1102 ++sequenceDepth;
1103 else
1104 --sequenceDepth;
1105
1106 if (sequenceDepth == 1) {
1107 // If this is the parent node of all the functions, we want to see them
1108 // early, so all call points have actual SPIR-V functions to reference.
1109 // In all cases, still let the traverser visit the children for us.
1110 makeFunctions(node->getAsAggregate()->getSequence());
1111
1112 // Also, we want all globals initializers to go into the entry of main(), before
1113 // anything else gets there, so visit out of order, doing them all now.
1114 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1115
1116 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1117 // so do them manually.
1118 visitFunctions(node->getAsAggregate()->getSequence());
1119
1120 return false;
1121 }
1122
1123 return true;
1124 }
1125 case glslang::EOpLinkerObjects:
1126 {
1127 if (visit == glslang::EvPreVisit)
1128 linkageOnly = true;
1129 else
1130 linkageOnly = false;
1131
1132 return true;
1133 }
1134 case glslang::EOpComma:
1135 {
1136 // processing from left to right naturally leaves the right-most
1137 // lying around in the access chain
1138 glslang::TIntermSequence& glslangOperands = node->getSequence();
1139 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1140 glslangOperands[i]->traverse(this);
1141
1142 return false;
1143 }
1144 case glslang::EOpFunction:
1145 if (visit == glslang::EvPreVisit) {
1146 if (isShaderEntrypoint(node)) {
1147 inMain = true;
1148 builder.setBuildPoint(shaderEntry->getLastBlock());
1149 } else {
1150 handleFunctionEntry(node);
1151 }
1152 } else {
1153 if (inMain)
1154 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001155 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001156 inMain = false;
1157 }
1158
1159 return true;
1160 case glslang::EOpParameters:
1161 // Parameters will have been consumed by EOpFunction processing, but not
1162 // the body, so we still visited the function node's children, making this
1163 // child redundant.
1164 return false;
1165 case glslang::EOpFunctionCall:
1166 {
1167 if (node->isUserDefined())
1168 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001169 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1170 if (result) {
1171 builder.clearAccessChain();
1172 builder.setAccessChainRValue(result);
1173 } else
1174 spv::MissingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001175
1176 return false;
1177 }
1178 case glslang::EOpConstructMat2x2:
1179 case glslang::EOpConstructMat2x3:
1180 case glslang::EOpConstructMat2x4:
1181 case glslang::EOpConstructMat3x2:
1182 case glslang::EOpConstructMat3x3:
1183 case glslang::EOpConstructMat3x4:
1184 case glslang::EOpConstructMat4x2:
1185 case glslang::EOpConstructMat4x3:
1186 case glslang::EOpConstructMat4x4:
1187 case glslang::EOpConstructDMat2x2:
1188 case glslang::EOpConstructDMat2x3:
1189 case glslang::EOpConstructDMat2x4:
1190 case glslang::EOpConstructDMat3x2:
1191 case glslang::EOpConstructDMat3x3:
1192 case glslang::EOpConstructDMat3x4:
1193 case glslang::EOpConstructDMat4x2:
1194 case glslang::EOpConstructDMat4x3:
1195 case glslang::EOpConstructDMat4x4:
1196 isMatrix = true;
1197 // fall through
1198 case glslang::EOpConstructFloat:
1199 case glslang::EOpConstructVec2:
1200 case glslang::EOpConstructVec3:
1201 case glslang::EOpConstructVec4:
1202 case glslang::EOpConstructDouble:
1203 case glslang::EOpConstructDVec2:
1204 case glslang::EOpConstructDVec3:
1205 case glslang::EOpConstructDVec4:
1206 case glslang::EOpConstructBool:
1207 case glslang::EOpConstructBVec2:
1208 case glslang::EOpConstructBVec3:
1209 case glslang::EOpConstructBVec4:
1210 case glslang::EOpConstructInt:
1211 case glslang::EOpConstructIVec2:
1212 case glslang::EOpConstructIVec3:
1213 case glslang::EOpConstructIVec4:
1214 case glslang::EOpConstructUint:
1215 case glslang::EOpConstructUVec2:
1216 case glslang::EOpConstructUVec3:
1217 case glslang::EOpConstructUVec4:
1218 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001219 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001220 {
1221 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001222 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001223 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1224 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001225 if (node->getOp() == glslang::EOpConstructTextureSampler)
1226 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1227 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001228 std::vector<spv::Id> constituents;
1229 for (int c = 0; c < (int)arguments.size(); ++c)
1230 constituents.push_back(arguments[c]);
1231 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001232 } else if (isMatrix)
1233 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1234 else
1235 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001236
1237 builder.clearAccessChain();
1238 builder.setAccessChainRValue(constructed);
1239
1240 return false;
1241 }
1242
1243 // These six are component-wise compares with component-wise results.
1244 // Forward on to createBinaryOperation(), requesting a vector result.
1245 case glslang::EOpLessThan:
1246 case glslang::EOpGreaterThan:
1247 case glslang::EOpLessThanEqual:
1248 case glslang::EOpGreaterThanEqual:
1249 case glslang::EOpVectorEqual:
1250 case glslang::EOpVectorNotEqual:
1251 {
1252 // Map the operation to a binary
1253 binOp = node->getOp();
1254 reduceComparison = false;
1255 switch (node->getOp()) {
1256 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1257 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1258 default: binOp = node->getOp(); break;
1259 }
1260
1261 break;
1262 }
1263 case glslang::EOpMul:
1264 // compontent-wise matrix multiply
1265 binOp = glslang::EOpMul;
1266 break;
1267 case glslang::EOpOuterProduct:
1268 // two vectors multiplied to make a matrix
1269 binOp = glslang::EOpOuterProduct;
1270 break;
1271 case glslang::EOpDot:
1272 {
1273 // for scalar dot product, use multiply
1274 glslang::TIntermSequence& glslangOperands = node->getSequence();
1275 if (! glslangOperands[0]->getAsTyped()->isVector())
1276 binOp = glslang::EOpMul;
1277 break;
1278 }
1279 case glslang::EOpMod:
1280 // when an aggregate, this is the floating-point mod built-in function,
1281 // which can be emitted by the one in createBinaryOperation()
1282 binOp = glslang::EOpMod;
1283 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001284 case glslang::EOpEmitVertex:
1285 case glslang::EOpEndPrimitive:
1286 case glslang::EOpBarrier:
1287 case glslang::EOpMemoryBarrier:
1288 case glslang::EOpMemoryBarrierAtomicCounter:
1289 case glslang::EOpMemoryBarrierBuffer:
1290 case glslang::EOpMemoryBarrierImage:
1291 case glslang::EOpMemoryBarrierShared:
1292 case glslang::EOpGroupMemoryBarrier:
1293 noReturnValue = true;
1294 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1295 break;
1296
John Kessenich426394d2015-07-23 10:22:48 -06001297 case glslang::EOpAtomicAdd:
1298 case glslang::EOpAtomicMin:
1299 case glslang::EOpAtomicMax:
1300 case glslang::EOpAtomicAnd:
1301 case glslang::EOpAtomicOr:
1302 case glslang::EOpAtomicXor:
1303 case glslang::EOpAtomicExchange:
1304 case glslang::EOpAtomicCompSwap:
1305 atomic = true;
1306 break;
1307
John Kessenich140f3df2015-06-26 16:58:36 -06001308 default:
1309 break;
1310 }
1311
1312 //
1313 // See if it maps to a regular operation.
1314 //
John Kessenich140f3df2015-06-26 16:58:36 -06001315 if (binOp != glslang::EOpNull) {
1316 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1317 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1318 assert(left && right);
1319
1320 builder.clearAccessChain();
1321 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001322 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001323
1324 builder.clearAccessChain();
1325 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001326 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001327
1328 result = createBinaryOperation(binOp, precision,
1329 convertGlslangToSpvType(node->getType()), leftId, rightId,
1330 left->getType().getBasicType(), reduceComparison);
1331
1332 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001333 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001334 builder.clearAccessChain();
1335 builder.setAccessChainRValue(result);
1336
1337 return false;
1338 }
1339
John Kessenich426394d2015-07-23 10:22:48 -06001340 //
1341 // Create the list of operands.
1342 //
John Kessenich140f3df2015-06-26 16:58:36 -06001343 glslang::TIntermSequence& glslangOperands = node->getSequence();
1344 std::vector<spv::Id> operands;
1345 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1346 builder.clearAccessChain();
1347 glslangOperands[arg]->traverse(this);
1348
1349 // special case l-value operands; there are just a few
1350 bool lvalue = false;
1351 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001352 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001353 case glslang::EOpModf:
1354 if (arg == 1)
1355 lvalue = true;
1356 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001357 case glslang::EOpInterpolateAtSample:
1358 case glslang::EOpInterpolateAtOffset:
1359 if (arg == 0)
1360 lvalue = true;
1361 break;
Rex Xud4782c12015-09-06 16:30:11 +08001362 case glslang::EOpAtomicAdd:
1363 case glslang::EOpAtomicMin:
1364 case glslang::EOpAtomicMax:
1365 case glslang::EOpAtomicAnd:
1366 case glslang::EOpAtomicOr:
1367 case glslang::EOpAtomicXor:
1368 case glslang::EOpAtomicExchange:
1369 case glslang::EOpAtomicCompSwap:
1370 if (arg == 0)
1371 lvalue = true;
1372 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001373 case glslang::EOpAddCarry:
1374 case glslang::EOpSubBorrow:
1375 if (arg == 2)
1376 lvalue = true;
1377 break;
1378 case glslang::EOpUMulExtended:
1379 case glslang::EOpIMulExtended:
1380 if (arg >= 2)
1381 lvalue = true;
1382 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001383 default:
1384 break;
1385 }
1386 if (lvalue)
1387 operands.push_back(builder.accessChainGetLValue());
1388 else
John Kessenich32cfd492016-02-02 12:37:46 -07001389 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001390 }
John Kessenich426394d2015-07-23 10:22:48 -06001391
1392 if (atomic) {
1393 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001394 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001395 } else {
1396 // Pass through to generic operations.
1397 switch (glslangOperands.size()) {
1398 case 0:
1399 result = createNoArgOperation(node->getOp());
1400 break;
1401 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001402 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001403 break;
1404 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001405 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001406 break;
1407 }
John Kessenich140f3df2015-06-26 16:58:36 -06001408 }
1409
1410 if (noReturnValue)
1411 return false;
1412
1413 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001414 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001415 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001416 } else {
1417 builder.clearAccessChain();
1418 builder.setAccessChainRValue(result);
1419 return false;
1420 }
1421}
1422
1423bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1424{
1425 // This path handles both if-then-else and ?:
1426 // The if-then-else has a node type of void, while
1427 // ?: has a non-void node type
1428 spv::Id result = 0;
1429 if (node->getBasicType() != glslang::EbtVoid) {
1430 // don't handle this as just on-the-fly temporaries, because there will be two names
1431 // and better to leave SSA to later passes
1432 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1433 }
1434
1435 // emit the condition before doing anything with selection
1436 node->getCondition()->traverse(this);
1437
1438 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001439 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001440
1441 if (node->getTrueBlock()) {
1442 // emit the "then" statement
1443 node->getTrueBlock()->traverse(this);
1444 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001445 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001446 }
1447
1448 if (node->getFalseBlock()) {
1449 ifBuilder.makeBeginElse();
1450 // emit the "else" statement
1451 node->getFalseBlock()->traverse(this);
1452 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001453 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001454 }
1455
1456 ifBuilder.makeEndIf();
1457
1458 if (result) {
1459 // GLSL only has r-values as the result of a :?, but
1460 // if we have an l-value, that can be more efficient if it will
1461 // become the base of a complex r-value expression, because the
1462 // next layer copies r-values into memory to use the access-chain mechanism
1463 builder.clearAccessChain();
1464 builder.setAccessChainLValue(result);
1465 }
1466
1467 return false;
1468}
1469
1470bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1471{
1472 // emit and get the condition before doing anything with switch
1473 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001474 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001475
1476 // browse the children to sort out code segments
1477 int defaultSegment = -1;
1478 std::vector<TIntermNode*> codeSegments;
1479 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1480 std::vector<int> caseValues;
1481 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1482 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1483 TIntermNode* child = *c;
1484 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001485 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001486 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001487 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001488 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1489 } else
1490 codeSegments.push_back(child);
1491 }
1492
1493 // handle the case where the last code segment is missing, due to no code
1494 // statements between the last case and the end of the switch statement
1495 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1496 (int)codeSegments.size() == defaultSegment)
1497 codeSegments.push_back(nullptr);
1498
1499 // make the switch statement
1500 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001501 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001502
1503 // emit all the code in the segments
1504 breakForLoop.push(false);
1505 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1506 builder.nextSwitchSegment(segmentBlocks, s);
1507 if (codeSegments[s])
1508 codeSegments[s]->traverse(this);
1509 else
1510 builder.addSwitchBreak();
1511 }
1512 breakForLoop.pop();
1513
1514 builder.endSwitch(segmentBlocks);
1515
1516 return false;
1517}
1518
1519void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1520{
1521 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001522 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001523
1524 builder.clearAccessChain();
1525 builder.setAccessChainRValue(constant);
1526}
1527
1528bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1529{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001530 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001531 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001532 // Spec requires back edges to target header blocks, and every header block
1533 // must dominate its merge block. Make a header block first to ensure these
1534 // conditions are met. By definition, it will contain OpLoopMerge, followed
1535 // by a block-ending branch. But we don't want to put any other body/test
1536 // instructions in it, since the body/test may have arbitrary instructions,
1537 // including merges of its own.
1538 builder.setBuildPoint(&blocks.head);
1539 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001540 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001541 spv::Block& test = builder.makeNewBlock();
1542 builder.createBranch(&test);
1543
1544 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001545 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001546 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001547 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001548 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1549
1550 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001551 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001552 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001553 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001554 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001555 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001556
1557 builder.setBuildPoint(&blocks.continue_target);
1558 if (node->getTerminal())
1559 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001560 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001561 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001562 builder.createBranch(&blocks.body);
1563
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001564 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001565 builder.setBuildPoint(&blocks.body);
1566 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001567 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001568 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001569 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001570
1571 builder.setBuildPoint(&blocks.continue_target);
1572 if (node->getTerminal())
1573 node->getTerminal()->traverse(this);
1574 if (node->getTest()) {
1575 node->getTest()->traverse(this);
1576 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001577 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001578 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001579 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001580 // TODO: unless there was a break/return/discard instruction
1581 // somewhere in the body, this is an infinite loop, so we should
1582 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001583 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001584 }
John Kessenich140f3df2015-06-26 16:58:36 -06001585 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001586 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001587 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001588 return false;
1589}
1590
1591bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1592{
1593 if (node->getExpression())
1594 node->getExpression()->traverse(this);
1595
1596 switch (node->getFlowOp()) {
1597 case glslang::EOpKill:
1598 builder.makeDiscard();
1599 break;
1600 case glslang::EOpBreak:
1601 if (breakForLoop.top())
1602 builder.createLoopExit();
1603 else
1604 builder.addSwitchBreak();
1605 break;
1606 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001607 builder.createLoopContinue();
1608 break;
1609 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001610 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001611 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001612 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001613 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001614
1615 builder.clearAccessChain();
1616 break;
1617
1618 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001619 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001620 break;
1621 }
1622
1623 return false;
1624}
1625
1626spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1627{
1628 // First, steer off constants, which are not SPIR-V variables, but
1629 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001630 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001631 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001632 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001633 }
1634
1635 // Now, handle actual variables
1636 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1637 spv::Id spvType = convertGlslangToSpvType(node->getType());
1638
1639 const char* name = node->getName().c_str();
1640 if (glslang::IsAnonymous(name))
1641 name = "";
1642
1643 return builder.createVariable(storageClass, spvType, name);
1644}
1645
1646// Return type Id of the sampled type.
1647spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1648{
1649 switch (sampler.type) {
1650 case glslang::EbtFloat: return builder.makeFloatType(32);
1651 case glslang::EbtInt: return builder.makeIntType(32);
1652 case glslang::EbtUint: return builder.makeUintType(32);
1653 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001654 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001655 return builder.makeFloatType(32);
1656 }
1657}
1658
John Kessenich3ac051e2015-12-20 11:29:16 -07001659// Convert from a glslang type to an SPV type, by calling into a
1660// recursive version of this function. This establishes the inherited
1661// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001662spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1663{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001664 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001665}
1666
1667// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001668// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001669spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001670{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001671 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001672
1673 switch (type.getBasicType()) {
1674 case glslang::EbtVoid:
1675 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001676 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001677 break;
1678 case glslang::EbtFloat:
1679 spvType = builder.makeFloatType(32);
1680 break;
1681 case glslang::EbtDouble:
1682 spvType = builder.makeFloatType(64);
1683 break;
1684 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001685 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1686 // a 32-bit int where non-0 means true.
1687 if (explicitLayout != glslang::ElpNone)
1688 spvType = builder.makeUintType(32);
1689 else
1690 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001691 break;
1692 case glslang::EbtInt:
1693 spvType = builder.makeIntType(32);
1694 break;
1695 case glslang::EbtUint:
1696 spvType = builder.makeUintType(32);
1697 break;
John Kessenich426394d2015-07-23 10:22:48 -06001698 case glslang::EbtAtomicUint:
1699 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1700 spvType = builder.makeUintType(32);
1701 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001702 case glslang::EbtSampler:
1703 {
1704 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001705 if (sampler.sampler) {
1706 // pure sampler
1707 spvType = builder.makeSamplerType();
1708 } else {
1709 // an image is present, make its type
1710 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1711 sampler.image ? 2 : 1, TranslateImageFormat(type));
1712 if (sampler.combined) {
1713 // already has both image and sampler, make the combined type
1714 spvType = builder.makeSampledImageType(spvType);
1715 }
John Kessenich55e7d112015-11-15 21:33:39 -07001716 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001717 }
John Kessenich140f3df2015-06-26 16:58:36 -06001718 break;
1719 case glslang::EbtStruct:
1720 case glslang::EbtBlock:
1721 {
1722 // If we've seen this struct type, return it
1723 const glslang::TTypeList* glslangStruct = type.getStruct();
1724 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001725
1726 // Try to share structs for different layouts, but not yet for other
1727 // kinds of qualification (primarily not yet including interpolant qualification).
1728 if (! HasNonLayoutQualifiers(qualifier))
1729 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1730 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001731 break;
1732
1733 // else, we haven't seen it...
1734
1735 // Create a vector of struct types for SPIR-V to consume
1736 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1737 if (type.getBasicType() == glslang::EbtBlock)
1738 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001739 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001740 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1741 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1742 if (glslangType.hiddenMember()) {
1743 ++memberDelta;
1744 if (type.getBasicType() == glslang::EbtBlock)
1745 memberRemapper[glslangStruct][i] = -1;
1746 } else {
1747 if (type.getBasicType() == glslang::EbtBlock)
1748 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001749 // modify just this child's view of the qualifier
1750 glslang::TQualifier subQualifier = glslangType.getQualifier();
1751 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001752
1753 // manually inherit location; it's more complex
1754 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1755 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1756 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001757 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001758
1759 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001760 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001761 }
1762 }
1763
1764 // Make the SPIR-V type
1765 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001766 if (! HasNonLayoutQualifiers(qualifier))
1767 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001768
1769 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001770 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001771 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001772 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1773 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1774 int member = i;
1775 if (type.getBasicType() == glslang::EbtBlock)
1776 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001777
John Kesseniche0b6cad2015-12-24 10:30:13 -07001778 // modify just this child's view of the qualifier
1779 glslang::TQualifier subQualifier = glslangType.getQualifier();
1780 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001781
John Kessenich140f3df2015-06-26 16:58:36 -06001782 // using -1 above to indicate a hidden member
1783 if (member >= 0) {
1784 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001785 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001786 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001787 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1788 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001789
Rex Xu1da878f2016-02-21 20:59:01 +08001790 if (qualifier.storage == glslang::EvqBuffer) {
1791 std::vector<spv::Decoration> memory;
1792 TranslateMemoryDecoration(subQualifier, memory);
1793 for (unsigned int i = 0; i < memory.size(); ++i)
1794 addMemberDecoration(spvType, member, memory[i]);
1795 }
1796
John Kessenich09677482016-02-19 12:21:50 -07001797 // compute location decoration; tricky based on whether inheritance is at play
1798 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1799 // probably move to the linker stage of the front end proper, and just have the
1800 // answer sitting already distributed throughout the individual member locations.
1801 int location = -1; // will only decorate if present or inherited
1802 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1803 location = subQualifier.layoutLocation;
1804 else if (qualifier.hasLocation()) // inheritance
1805 location = qualifier.layoutLocation + locationOffset;
1806 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001807 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001808 if (location >= 0)
1809 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1810
1811 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001812 if (glslangType.getQualifier().hasComponent())
1813 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1814 if (glslangType.getQualifier().hasXfbOffset())
1815 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001816 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001817 // figure out what to do with offset, which is accumulating
1818 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001819 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001820 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001821 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001822 offset = nextOffset;
1823 }
John Kessenich140f3df2015-06-26 16:58:36 -06001824
John Kessenichf85e8062015-12-19 13:57:10 -07001825 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001826 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001827
John Kessenich140f3df2015-06-26 16:58:36 -06001828 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001829 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1830 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001831 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001832 }
1833 }
1834
1835 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001836 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001837 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001838 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001839 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001840 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001841 }
John Kessenich140f3df2015-06-26 16:58:36 -06001842 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001843 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001844 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001845 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001846 if (type.getQualifier().hasXfbBuffer())
1847 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1848 }
1849 }
1850 break;
1851 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001852 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001853 break;
1854 }
1855
1856 if (type.isMatrix())
1857 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1858 else {
1859 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1860 if (type.getVectorSize() > 1)
1861 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1862 }
1863
1864 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001865 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1866
John Kessenichc9a80832015-09-12 12:17:44 -06001867 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001868 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001869 // We need to decorate array strides for types needing explicit layout, except blocks.
1870 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001871 // Use a dummy glslang type for querying internal strides of
1872 // arrays of arrays, but using just a one-dimensional array.
1873 glslang::TType simpleArrayType(type, 0); // deference type of the array
1874 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1875 simpleArrayType.getArraySizes().dereference();
1876
1877 // Will compute the higher-order strides here, rather than making a whole
1878 // pile of types and doing repetitive recursion on their contents.
1879 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1880 }
John Kessenichf8842e52016-01-04 19:22:56 -07001881
1882 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001883 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001884 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001885 if (stride > 0)
1886 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001887 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001888 }
1889 } else {
1890 // single-dimensional array, and don't yet have stride
1891
John Kessenichf8842e52016-01-04 19:22:56 -07001892 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001893 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1894 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001895 }
John Kessenich31ed4832015-09-09 17:51:38 -06001896
John Kessenichc9a80832015-09-12 12:17:44 -06001897 // Do the outer dimension, which might not be known for a runtime-sized array
1898 if (type.isRuntimeSizedArray()) {
1899 spvType = builder.makeRuntimeArray(spvType);
1900 } else {
1901 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001902 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001903 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001904 if (stride > 0)
1905 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001906 }
1907
1908 return spvType;
1909}
1910
John Kessenich6c292d32016-02-15 20:58:50 -07001911// Turn the expression forming the array size into an id.
1912// This is not quite trivial, because of specialization constants.
1913// Sometimes, a raw constant is turned into an Id, and sometimes
1914// a specialization constant expression is.
1915spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1916{
1917 // First, see if this is sized with a node, meaning a specialization constant:
1918 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1919 if (specNode != nullptr) {
1920 builder.clearAccessChain();
1921 specNode->traverse(this);
1922 return accessChainLoad(specNode->getAsTyped()->getType());
1923 }
1924
1925 // Otherwise, need a compile-time (front end) size, get it:
1926 int size = arraySizes.getDimSize(dim);
1927 assert(size > 0);
1928 return builder.makeUintConstant(size);
1929}
1930
John Kessenich103bef92016-02-08 21:38:15 -07001931// Wrap the builder's accessChainLoad to:
1932// - localize handling of RelaxedPrecision
1933// - use the SPIR-V inferred type instead of another conversion of the glslang type
1934// (avoids unnecessary work and possible type punning for structures)
1935// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001936spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1937{
John Kessenich103bef92016-02-08 21:38:15 -07001938 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1939 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1940
1941 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08001942 if (type.getBasicType() == glslang::EbtBool) {
1943 if (builder.isScalarType(nominalTypeId)) {
1944 // Conversion for bool
1945 spv::Id boolType = builder.makeBoolType();
1946 if (nominalTypeId != boolType)
1947 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
1948 } else if (builder.isVectorType(nominalTypeId)) {
1949 // Conversion for bvec
1950 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1951 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1952 if (nominalTypeId != bvecType)
1953 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
1954 }
1955 }
John Kessenich103bef92016-02-08 21:38:15 -07001956
1957 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07001958}
1959
Rex Xu27253232016-02-23 17:51:09 +08001960// Wrap the builder's accessChainStore to:
1961// - do conversion of concrete to abstract type
1962void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
1963{
1964 // Need to convert to abstract types when necessary
1965 if (type.getBasicType() == glslang::EbtBool) {
1966 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1967
1968 if (builder.isScalarType(nominalTypeId)) {
1969 // Conversion for bool
1970 spv::Id boolType = builder.makeBoolType();
1971 if (nominalTypeId != boolType) {
1972 spv::Id zero = builder.makeUintConstant(0);
1973 spv::Id one = builder.makeUintConstant(1);
1974 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
1975 }
1976 } else if (builder.isVectorType(nominalTypeId)) {
1977 // Conversion for bvec
1978 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1979 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1980 if (nominalTypeId != bvecType) {
1981 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
1982 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
1983 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
1984 }
1985 }
1986 }
1987
1988 builder.accessChainStore(rvalue);
1989}
1990
John Kessenichf85e8062015-12-19 13:57:10 -07001991// Decide whether or not this type should be
1992// decorated with offsets and strides, and if so
1993// whether std140 or std430 rules should be applied.
1994glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001995{
John Kessenichf85e8062015-12-19 13:57:10 -07001996 // has to be a block
1997 if (type.getBasicType() != glslang::EbtBlock)
1998 return glslang::ElpNone;
1999
2000 // has to be a uniform or buffer block
2001 if (type.getQualifier().storage != glslang::EvqUniform &&
2002 type.getQualifier().storage != glslang::EvqBuffer)
2003 return glslang::ElpNone;
2004
2005 // return the layout to use
2006 switch (type.getQualifier().layoutPacking) {
2007 case glslang::ElpStd140:
2008 case glslang::ElpStd430:
2009 return type.getQualifier().layoutPacking;
2010 default:
2011 return glslang::ElpNone;
2012 }
John Kessenich31ed4832015-09-09 17:51:38 -06002013}
2014
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002015// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002016int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002017{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002018 int size;
John Kessenich49987892015-12-29 17:11:44 -07002019 int stride;
2020 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002021
2022 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002023}
2024
John Kessenich49987892015-12-29 17:11:44 -07002025// 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 -07002026// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002027int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002028{
John Kessenich49987892015-12-29 17:11:44 -07002029 glslang::TType elementType;
2030 elementType.shallowCopy(matrixType);
2031 elementType.clearArraySizes();
2032
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002033 int size;
John Kessenich49987892015-12-29 17:11:44 -07002034 int stride;
2035 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2036
2037 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002038}
2039
John Kessenich5e4b1242015-08-06 22:53:06 -06002040// Given a member type of a struct, realign the current offset for it, and compute
2041// the next (not yet aligned) offset for the next member, which will get aligned
2042// on the next call.
2043// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2044// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2045// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002046void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002047 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002048{
2049 // this will get a positive value when deemed necessary
2050 nextOffset = -1;
2051
John Kessenich5e4b1242015-08-06 22:53:06 -06002052 // override anything in currentOffset with user-set offset
2053 if (memberType.getQualifier().hasOffset())
2054 currentOffset = memberType.getQualifier().layoutOffset;
2055
2056 // It could be that current linker usage in glslang updated all the layoutOffset,
2057 // in which case the following code does not matter. But, that's not quite right
2058 // once cross-compilation unit GLSL validation is done, as the original user
2059 // settings are needed in layoutOffset, and then the following will come into play.
2060
John Kessenichf85e8062015-12-19 13:57:10 -07002061 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002062 if (! memberType.getQualifier().hasOffset())
2063 currentOffset = -1;
2064
2065 return;
2066 }
2067
John Kessenichf85e8062015-12-19 13:57:10 -07002068 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002069 if (currentOffset < 0)
2070 currentOffset = 0;
2071
2072 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2073 // but possibly not yet correctly aligned.
2074
2075 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002076 int dummyStride;
2077 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002078 glslang::RoundToPow2(currentOffset, memberAlignment);
2079 nextOffset = currentOffset + memberSize;
2080}
2081
John Kessenich140f3df2015-06-26 16:58:36 -06002082bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2083{
2084 return node->getName() == "main(";
2085}
2086
2087// Make all the functions, skeletally, without actually visiting their bodies.
2088void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2089{
2090 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2091 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2092 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2093 continue;
2094
2095 // We're on a user function. Set up the basic interface for the function now,
2096 // so that it's available to call.
2097 // Translating the body will happen later.
2098 //
2099 // Typically (except for a "const in" parameter), an address will be passed to the
2100 // function. What it is an address of varies:
2101 //
2102 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2103 // so that write needs to be to a copy, hence the address of a copy works.
2104 //
2105 // - "const in" parameters can just be the r-value, as no writes need occur.
2106 //
2107 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2108 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2109
2110 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002111 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002112 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2113
2114 for (int p = 0; p < (int)parameters.size(); ++p) {
2115 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2116 spv::Id typeId = convertGlslangToSpvType(paramType);
2117 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2118 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2119 else
2120 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002121 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002122 paramTypes.push_back(typeId);
2123 }
2124
2125 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002126 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2127 convertGlslangToSpvType(glslFunction->getType()),
2128 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002129
2130 // Track function to emit/call later
2131 functionMap[glslFunction->getName().c_str()] = function;
2132
2133 // Set the parameter id's
2134 for (int p = 0; p < (int)parameters.size(); ++p) {
2135 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2136 // give a name too
2137 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2138 }
2139 }
2140}
2141
2142// Process all the initializers, while skipping the functions and link objects
2143void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2144{
2145 builder.setBuildPoint(shaderEntry->getLastBlock());
2146 for (int i = 0; i < (int)initializers.size(); ++i) {
2147 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2148 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2149
2150 // We're on a top-level node that's not a function. Treat as an initializer, whose
2151 // code goes into the beginning of main.
2152 initializer->traverse(this);
2153 }
2154 }
2155}
2156
2157// Process all the functions, while skipping initializers.
2158void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2159{
2160 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2161 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2162 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2163 node->traverse(this);
2164 }
2165}
2166
2167void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2168{
2169 // SPIR-V functions should already be in the functionMap from the prepass
2170 // that called makeFunctions().
2171 spv::Function* function = functionMap[node->getName().c_str()];
2172 spv::Block* functionBlock = function->getEntryBlock();
2173 builder.setBuildPoint(functionBlock);
2174}
2175
Rex Xu04db3f52015-09-16 11:44:02 +08002176void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002177{
Rex Xufc618912015-09-09 16:42:49 +08002178 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002179
2180 glslang::TSampler sampler = {};
2181 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002182 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002183 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2184 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2185 }
2186
John Kessenich140f3df2015-06-26 16:58:36 -06002187 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2188 builder.clearAccessChain();
2189 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002190
2191 // Special case l-value operands
2192 bool lvalue = false;
2193 switch (node.getOp()) {
2194 case glslang::EOpImageAtomicAdd:
2195 case glslang::EOpImageAtomicMin:
2196 case glslang::EOpImageAtomicMax:
2197 case glslang::EOpImageAtomicAnd:
2198 case glslang::EOpImageAtomicOr:
2199 case glslang::EOpImageAtomicXor:
2200 case glslang::EOpImageAtomicExchange:
2201 case glslang::EOpImageAtomicCompSwap:
2202 if (i == 0)
2203 lvalue = true;
2204 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002205 case glslang::EOpSparseImageLoad:
2206 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2207 lvalue = true;
2208 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002209 case glslang::EOpSparseTexture:
2210 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2211 lvalue = true;
2212 break;
2213 case glslang::EOpSparseTextureClamp:
2214 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2215 lvalue = true;
2216 break;
2217 case glslang::EOpSparseTextureLod:
2218 case glslang::EOpSparseTextureOffset:
2219 if (i == 3)
2220 lvalue = true;
2221 break;
2222 case glslang::EOpSparseTextureFetch:
2223 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2224 lvalue = true;
2225 break;
2226 case glslang::EOpSparseTextureFetchOffset:
2227 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2228 lvalue = true;
2229 break;
2230 case glslang::EOpSparseTextureLodOffset:
2231 case glslang::EOpSparseTextureGrad:
2232 case glslang::EOpSparseTextureOffsetClamp:
2233 if (i == 4)
2234 lvalue = true;
2235 break;
2236 case glslang::EOpSparseTextureGradOffset:
2237 case glslang::EOpSparseTextureGradClamp:
2238 if (i == 5)
2239 lvalue = true;
2240 break;
2241 case glslang::EOpSparseTextureGradOffsetClamp:
2242 if (i == 6)
2243 lvalue = true;
2244 break;
2245 case glslang::EOpSparseTextureGather:
2246 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2247 lvalue = true;
2248 break;
2249 case glslang::EOpSparseTextureGatherOffset:
2250 case glslang::EOpSparseTextureGatherOffsets:
2251 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2252 lvalue = true;
2253 break;
Rex Xufc618912015-09-09 16:42:49 +08002254 default:
2255 break;
2256 }
2257
Rex Xu6b86d492015-09-16 17:48:22 +08002258 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002259 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002260 else
John Kessenich32cfd492016-02-02 12:37:46 -07002261 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002262 }
2263}
2264
John Kessenichfc51d282015-08-19 13:34:18 -06002265void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002266{
John Kessenichfc51d282015-08-19 13:34:18 -06002267 builder.clearAccessChain();
2268 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002269 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002270}
John Kessenich140f3df2015-06-26 16:58:36 -06002271
John Kessenichfc51d282015-08-19 13:34:18 -06002272spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2273{
Rex Xufc618912015-09-09 16:42:49 +08002274 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002275 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002276 }
2277
John Kessenichfc51d282015-08-19 13:34:18 -06002278 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002279 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2280 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2281 std::vector<spv::Id> arguments;
2282 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002283 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002284 else
2285 translateArguments(*node->getAsUnaryNode(), arguments);
2286 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2287
2288 spv::Builder::TextureParameters params = { };
2289 params.sampler = arguments[0];
2290
Rex Xu04db3f52015-09-16 11:44:02 +08002291 glslang::TCrackedTextureOp cracked;
2292 node->crackTexture(sampler, cracked);
2293
John Kessenichfc51d282015-08-19 13:34:18 -06002294 // Check for queries
2295 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002296 // a sampled image needs to have the image extracted first
2297 if (builder.isSampledImage(params.sampler))
2298 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002299 switch (node->getOp()) {
2300 case glslang::EOpImageQuerySize:
2301 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002302 if (arguments.size() > 1) {
2303 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002304 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002305 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002306 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002307 case glslang::EOpImageQuerySamples:
2308 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002309 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002310 case glslang::EOpTextureQueryLod:
2311 params.coords = arguments[1];
2312 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2313 case glslang::EOpTextureQueryLevels:
2314 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002315 case glslang::EOpSparseTexelsResident:
2316 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002317 default:
2318 assert(0);
2319 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002320 }
John Kessenich140f3df2015-06-26 16:58:36 -06002321 }
2322
Rex Xufc618912015-09-09 16:42:49 +08002323 // Check for image functions other than queries
2324 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002325 std::vector<spv::Id> operands;
2326 auto opIt = arguments.begin();
2327 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002328
2329 // Handle subpass operations
2330 // TODO: GLSL should change to have the "MS" only on the type rather than the
2331 // built-in function.
2332 if (cracked.subpass) {
2333 // add on the (0,0) coordinate
2334 spv::Id zero = builder.makeIntConstant(0);
2335 std::vector<spv::Id> comps;
2336 comps.push_back(zero);
2337 comps.push_back(zero);
2338 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2339 if (sampler.ms) {
2340 operands.push_back(spv::ImageOperandsSampleMask);
2341 operands.push_back(*(opIt++));
2342 }
2343 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2344 }
2345
John Kessenich56bab042015-09-16 10:54:31 -06002346 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002347 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002348 if (sampler.ms) {
2349 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002350 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002351 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002352 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2353 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002354 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002355 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002356 if (sampler.ms) {
2357 operands.push_back(*(opIt + 1));
2358 operands.push_back(spv::ImageOperandsSampleMask);
2359 operands.push_back(*opIt);
2360 } else
2361 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002362 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002363 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2364 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002365 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002366 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2367 builder.addCapability(spv::CapabilitySparseResidency);
2368 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2369 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2370
2371 if (sampler.ms) {
2372 operands.push_back(spv::ImageOperandsSampleMask);
2373 operands.push_back(*opIt++);
2374 }
2375
2376 // Create the return type that was a special structure
2377 spv::Id texelOut = *opIt;
2378 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2379 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2380 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2381
2382 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2383
2384 // Decode the return type
2385 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2386 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002387 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002388 // Process image atomic operations
2389
2390 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2391 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002392 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002393
Rex Xufc618912015-09-09 16:42:49 +08002394 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002395 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002396
2397 std::vector<spv::Id> operands;
2398 operands.push_back(pointer);
2399 for (; opIt != arguments.end(); ++opIt)
2400 operands.push_back(*opIt);
2401
Rex Xu04db3f52015-09-16 11:44:02 +08002402 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002403 }
2404 }
2405
2406 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002407 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002408 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2409
John Kessenichfc51d282015-08-19 13:34:18 -06002410 // check for bias argument
2411 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002412 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002413 int nonBiasArgCount = 2;
2414 if (cracked.offset)
2415 ++nonBiasArgCount;
2416 if (cracked.grad)
2417 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002418 if (cracked.lodClamp)
2419 ++nonBiasArgCount;
2420 if (sparse)
2421 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002422
2423 if ((int)arguments.size() > nonBiasArgCount)
2424 bias = true;
2425 }
2426
John Kessenichfc51d282015-08-19 13:34:18 -06002427 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002428
John Kessenichfc51d282015-08-19 13:34:18 -06002429 params.coords = arguments[1];
2430 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002431 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002432
2433 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002434 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002435 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002436 ++extraArgs;
2437 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002438 params.Dref = arguments[2];
2439 ++extraArgs;
2440 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002441 std::vector<spv::Id> indexes;
2442 int comp;
2443 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002444 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002445 else
2446 comp = builder.getNumComponents(params.coords) - 1;
2447 indexes.push_back(comp);
2448 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2449 }
2450 if (cracked.lod) {
2451 params.lod = arguments[2];
2452 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002453 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2454 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2455 noImplicitLod = true;
2456 }
2457 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002458 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002459 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002460 }
2461 if (cracked.grad) {
2462 params.gradX = arguments[2 + extraArgs];
2463 params.gradY = arguments[3 + extraArgs];
2464 extraArgs += 2;
2465 }
John Kessenich55e7d112015-11-15 21:33:39 -07002466 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002467 params.offset = arguments[2 + extraArgs];
2468 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002469 } else if (cracked.offsets) {
2470 params.offsets = arguments[2 + extraArgs];
2471 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002472 }
Rex Xu48edadf2015-12-31 16:11:41 +08002473 if (cracked.lodClamp) {
2474 params.lodClamp = arguments[2 + extraArgs];
2475 ++extraArgs;
2476 }
2477 if (sparse) {
2478 params.texelOut = arguments[2 + extraArgs];
2479 ++extraArgs;
2480 }
John Kessenichfc51d282015-08-19 13:34:18 -06002481 if (bias) {
2482 params.bias = arguments[2 + extraArgs];
2483 ++extraArgs;
2484 }
John Kessenich55e7d112015-11-15 21:33:39 -07002485 if (cracked.gather && ! sampler.shadow) {
2486 // default component is 0, if missing, otherwise an argument
2487 if (2 + extraArgs < (int)arguments.size()) {
2488 params.comp = arguments[2 + extraArgs];
2489 ++extraArgs;
2490 } else {
2491 params.comp = builder.makeIntConstant(0);
2492 }
2493 }
John Kessenichfc51d282015-08-19 13:34:18 -06002494
John Kessenich019f08f2016-02-15 15:40:42 -07002495 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002496}
2497
2498spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2499{
2500 // Grab the function's pointer from the previously created function
2501 spv::Function* function = functionMap[node->getName().c_str()];
2502 if (! function)
2503 return 0;
2504
2505 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2506 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2507
2508 // See comments in makeFunctions() for details about the semantics for parameter passing.
2509 //
2510 // These imply we need a four step process:
2511 // 1. Evaluate the arguments
2512 // 2. Allocate and make copies of in, out, and inout arguments
2513 // 3. Make the call
2514 // 4. Copy back the results
2515
2516 // 1. Evaluate the arguments
2517 std::vector<spv::Builder::AccessChain> lValues;
2518 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002519 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002520 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2521 // build l-value
2522 builder.clearAccessChain();
2523 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002524 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002525 // keep outputs as l-values, evaluate input-only as r-values
2526 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2527 // save l-value
2528 lValues.push_back(builder.getAccessChain());
2529 } else {
2530 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002531 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002532 }
2533 }
2534
2535 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2536 // copy the original into that space.
2537 //
2538 // Also, build up the list of actual arguments to pass in for the call
2539 int lValueCount = 0;
2540 int rValueCount = 0;
2541 std::vector<spv::Id> spvArgs;
2542 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2543 spv::Id arg;
2544 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2545 // need space to hold the copy
2546 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2547 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2548 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2549 // need to copy the input into output space
2550 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002551 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002552 builder.createStore(copy, arg);
2553 }
2554 ++lValueCount;
2555 } else {
2556 arg = rValues[rValueCount];
2557 ++rValueCount;
2558 }
2559 spvArgs.push_back(arg);
2560 }
2561
2562 // 3. Make the call.
2563 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002564 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002565
2566 // 4. Copy back out an "out" arguments.
2567 lValueCount = 0;
2568 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2569 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2570 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2571 spv::Id copy = builder.createLoad(spvArgs[a]);
2572 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002573 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002574 }
2575 ++lValueCount;
2576 }
2577 }
2578
2579 return result;
2580}
2581
2582// Translate AST operation to SPV operation, already having SPV-based operands/types.
2583spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2584 spv::Id typeId, spv::Id left, spv::Id right,
2585 glslang::TBasicType typeProxy, bool reduceComparison)
2586{
2587 bool isUnsigned = typeProxy == glslang::EbtUint;
2588 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2589
2590 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002591 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002592 bool comparison = false;
2593
2594 switch (op) {
2595 case glslang::EOpAdd:
2596 case glslang::EOpAddAssign:
2597 if (isFloat)
2598 binOp = spv::OpFAdd;
2599 else
2600 binOp = spv::OpIAdd;
2601 break;
2602 case glslang::EOpSub:
2603 case glslang::EOpSubAssign:
2604 if (isFloat)
2605 binOp = spv::OpFSub;
2606 else
2607 binOp = spv::OpISub;
2608 break;
2609 case glslang::EOpMul:
2610 case glslang::EOpMulAssign:
2611 if (isFloat)
2612 binOp = spv::OpFMul;
2613 else
2614 binOp = spv::OpIMul;
2615 break;
2616 case glslang::EOpVectorTimesScalar:
2617 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002618 if (isFloat) {
2619 if (builder.isVector(right))
2620 std::swap(left, right);
2621 assert(builder.isScalar(right));
2622 needMatchingVectors = false;
2623 binOp = spv::OpVectorTimesScalar;
2624 } else
2625 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002626 break;
2627 case glslang::EOpVectorTimesMatrix:
2628 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002629 binOp = spv::OpVectorTimesMatrix;
2630 break;
2631 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002632 binOp = spv::OpMatrixTimesVector;
2633 break;
2634 case glslang::EOpMatrixTimesScalar:
2635 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002636 binOp = spv::OpMatrixTimesScalar;
2637 break;
2638 case glslang::EOpMatrixTimesMatrix:
2639 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002640 binOp = spv::OpMatrixTimesMatrix;
2641 break;
2642 case glslang::EOpOuterProduct:
2643 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002644 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002645 break;
2646
2647 case glslang::EOpDiv:
2648 case glslang::EOpDivAssign:
2649 if (isFloat)
2650 binOp = spv::OpFDiv;
2651 else if (isUnsigned)
2652 binOp = spv::OpUDiv;
2653 else
2654 binOp = spv::OpSDiv;
2655 break;
2656 case glslang::EOpMod:
2657 case glslang::EOpModAssign:
2658 if (isFloat)
2659 binOp = spv::OpFMod;
2660 else if (isUnsigned)
2661 binOp = spv::OpUMod;
2662 else
2663 binOp = spv::OpSMod;
2664 break;
2665 case glslang::EOpRightShift:
2666 case glslang::EOpRightShiftAssign:
2667 if (isUnsigned)
2668 binOp = spv::OpShiftRightLogical;
2669 else
2670 binOp = spv::OpShiftRightArithmetic;
2671 break;
2672 case glslang::EOpLeftShift:
2673 case glslang::EOpLeftShiftAssign:
2674 binOp = spv::OpShiftLeftLogical;
2675 break;
2676 case glslang::EOpAnd:
2677 case glslang::EOpAndAssign:
2678 binOp = spv::OpBitwiseAnd;
2679 break;
2680 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002681 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002682 binOp = spv::OpLogicalAnd;
2683 break;
2684 case glslang::EOpInclusiveOr:
2685 case glslang::EOpInclusiveOrAssign:
2686 binOp = spv::OpBitwiseOr;
2687 break;
2688 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002689 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002690 binOp = spv::OpLogicalOr;
2691 break;
2692 case glslang::EOpExclusiveOr:
2693 case glslang::EOpExclusiveOrAssign:
2694 binOp = spv::OpBitwiseXor;
2695 break;
2696 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002697 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002698 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002699 break;
2700
2701 case glslang::EOpLessThan:
2702 case glslang::EOpGreaterThan:
2703 case glslang::EOpLessThanEqual:
2704 case glslang::EOpGreaterThanEqual:
2705 case glslang::EOpEqual:
2706 case glslang::EOpNotEqual:
2707 case glslang::EOpVectorEqual:
2708 case glslang::EOpVectorNotEqual:
2709 comparison = true;
2710 break;
2711 default:
2712 break;
2713 }
2714
John Kessenich7c1aa102015-10-15 13:29:11 -06002715 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002716 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002717 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002718 if (builder.isMatrix(left) || builder.isMatrix(right))
2719 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002720
2721 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002722 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002723 builder.promoteScalar(precision, left, right);
2724
John Kessenich32cfd492016-02-02 12:37:46 -07002725 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002726 }
2727
2728 if (! comparison)
2729 return 0;
2730
John Kessenich7c1aa102015-10-15 13:29:11 -06002731 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002732
2733 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2734 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2735
John Kessenich22118352015-12-21 20:54:09 -07002736 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002737 }
2738
2739 switch (op) {
2740 case glslang::EOpLessThan:
2741 if (isFloat)
2742 binOp = spv::OpFOrdLessThan;
2743 else if (isUnsigned)
2744 binOp = spv::OpULessThan;
2745 else
2746 binOp = spv::OpSLessThan;
2747 break;
2748 case glslang::EOpGreaterThan:
2749 if (isFloat)
2750 binOp = spv::OpFOrdGreaterThan;
2751 else if (isUnsigned)
2752 binOp = spv::OpUGreaterThan;
2753 else
2754 binOp = spv::OpSGreaterThan;
2755 break;
2756 case glslang::EOpLessThanEqual:
2757 if (isFloat)
2758 binOp = spv::OpFOrdLessThanEqual;
2759 else if (isUnsigned)
2760 binOp = spv::OpULessThanEqual;
2761 else
2762 binOp = spv::OpSLessThanEqual;
2763 break;
2764 case glslang::EOpGreaterThanEqual:
2765 if (isFloat)
2766 binOp = spv::OpFOrdGreaterThanEqual;
2767 else if (isUnsigned)
2768 binOp = spv::OpUGreaterThanEqual;
2769 else
2770 binOp = spv::OpSGreaterThanEqual;
2771 break;
2772 case glslang::EOpEqual:
2773 case glslang::EOpVectorEqual:
2774 if (isFloat)
2775 binOp = spv::OpFOrdEqual;
2776 else
2777 binOp = spv::OpIEqual;
2778 break;
2779 case glslang::EOpNotEqual:
2780 case glslang::EOpVectorNotEqual:
2781 if (isFloat)
2782 binOp = spv::OpFOrdNotEqual;
2783 else
2784 binOp = spv::OpINotEqual;
2785 break;
2786 default:
2787 break;
2788 }
2789
John Kessenich32cfd492016-02-02 12:37:46 -07002790 if (binOp != spv::OpNop)
2791 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002792
2793 return 0;
2794}
2795
John Kessenich04bb8a02015-12-12 12:28:14 -07002796//
2797// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2798// These can be any of:
2799//
2800// matrix * scalar
2801// scalar * matrix
2802// matrix * matrix linear algebraic
2803// matrix * vector
2804// vector * matrix
2805// matrix * matrix componentwise
2806// matrix op matrix op in {+, -, /}
2807// matrix op scalar op in {+, -, /}
2808// scalar op matrix op in {+, -, /}
2809//
2810spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2811{
2812 bool firstClass = true;
2813
2814 // First, handle first-class matrix operations (* and matrix/scalar)
2815 switch (op) {
2816 case spv::OpFDiv:
2817 if (builder.isMatrix(left) && builder.isScalar(right)) {
2818 // turn matrix / scalar into a multiply...
2819 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2820 op = spv::OpMatrixTimesScalar;
2821 } else
2822 firstClass = false;
2823 break;
2824 case spv::OpMatrixTimesScalar:
2825 if (builder.isMatrix(right))
2826 std::swap(left, right);
2827 assert(builder.isScalar(right));
2828 break;
2829 case spv::OpVectorTimesMatrix:
2830 assert(builder.isVector(left));
2831 assert(builder.isMatrix(right));
2832 break;
2833 case spv::OpMatrixTimesVector:
2834 assert(builder.isMatrix(left));
2835 assert(builder.isVector(right));
2836 break;
2837 case spv::OpMatrixTimesMatrix:
2838 assert(builder.isMatrix(left));
2839 assert(builder.isMatrix(right));
2840 break;
2841 default:
2842 firstClass = false;
2843 break;
2844 }
2845
John Kessenich32cfd492016-02-02 12:37:46 -07002846 if (firstClass)
2847 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002848
2849 // Handle component-wise +, -, *, and / for all combinations of type.
2850 // The result type of all of them is the same type as the (a) matrix operand.
2851 // The algorithm is to:
2852 // - break the matrix(es) into vectors
2853 // - smear any scalar to a vector
2854 // - do vector operations
2855 // - make a matrix out the vector results
2856 switch (op) {
2857 case spv::OpFAdd:
2858 case spv::OpFSub:
2859 case spv::OpFDiv:
2860 case spv::OpFMul:
2861 {
2862 // one time set up...
2863 bool leftMat = builder.isMatrix(left);
2864 bool rightMat = builder.isMatrix(right);
2865 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2866 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2867 spv::Id scalarType = builder.getScalarTypeId(typeId);
2868 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2869 std::vector<spv::Id> results;
2870 spv::Id smearVec = spv::NoResult;
2871 if (builder.isScalar(left))
2872 smearVec = builder.smearScalar(precision, left, vecType);
2873 else if (builder.isScalar(right))
2874 smearVec = builder.smearScalar(precision, right, vecType);
2875
2876 // do each vector op
2877 for (unsigned int c = 0; c < numCols; ++c) {
2878 std::vector<unsigned int> indexes;
2879 indexes.push_back(c);
2880 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2881 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2882 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2883 builder.setPrecision(results.back(), precision);
2884 }
2885
2886 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002887 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002888 }
2889 default:
2890 assert(0);
2891 return spv::NoResult;
2892 }
2893}
2894
Rex Xu04db3f52015-09-16 11:44:02 +08002895spv::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 -06002896{
2897 spv::Op unaryOp = spv::OpNop;
2898 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002899 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002900 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002901
2902 switch (op) {
2903 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002904 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002905 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002906 if (builder.isMatrixType(typeId))
2907 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2908 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002909 unaryOp = spv::OpSNegate;
2910 break;
2911
2912 case glslang::EOpLogicalNot:
2913 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002914 unaryOp = spv::OpLogicalNot;
2915 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002916 case glslang::EOpBitwiseNot:
2917 unaryOp = spv::OpNot;
2918 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002919
John Kessenich140f3df2015-06-26 16:58:36 -06002920 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002921 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002922 break;
2923 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002924 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002925 break;
2926 case glslang::EOpTranspose:
2927 unaryOp = spv::OpTranspose;
2928 break;
2929
2930 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002931 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002932 break;
2933 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002934 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002935 break;
2936 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002937 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002938 break;
2939 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002940 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002941 break;
2942 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002943 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002944 break;
2945 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002946 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002947 break;
2948 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002949 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002950 break;
2951 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002952 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002953 break;
2954
2955 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002956 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002957 break;
2958 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002959 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002960 break;
2961 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002962 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002963 break;
2964 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002965 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002966 break;
2967 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002968 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002969 break;
2970 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002971 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002972 break;
2973
2974 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002975 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002976 break;
2977 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002978 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002979 break;
2980
2981 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002982 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002983 break;
2984 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002985 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002986 break;
2987 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002988 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002989 break;
2990 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002991 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002992 break;
2993 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002994 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002995 break;
2996 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002997 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002998 break;
2999
3000 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003001 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003002 break;
3003 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003004 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003005 break;
3006 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003007 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003008 break;
3009 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003010 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003011 break;
3012 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003013 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003014 break;
3015 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003016 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003017 break;
3018
3019 case glslang::EOpIsNan:
3020 unaryOp = spv::OpIsNan;
3021 break;
3022 case glslang::EOpIsInf:
3023 unaryOp = spv::OpIsInf;
3024 break;
3025
Rex Xucbc426e2015-12-15 16:03:10 +08003026 case glslang::EOpFloatBitsToInt:
3027 case glslang::EOpFloatBitsToUint:
3028 case glslang::EOpIntBitsToFloat:
3029 case glslang::EOpUintBitsToFloat:
3030 unaryOp = spv::OpBitcast;
3031 break;
3032
John Kessenich140f3df2015-06-26 16:58:36 -06003033 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003034 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003035 break;
3036 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003037 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003038 break;
3039 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003040 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003041 break;
3042 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003043 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003044 break;
3045 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003046 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003047 break;
3048 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003049 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003050 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003051 case glslang::EOpPackSnorm4x8:
3052 libCall = spv::GLSLstd450PackSnorm4x8;
3053 break;
3054 case glslang::EOpUnpackSnorm4x8:
3055 libCall = spv::GLSLstd450UnpackSnorm4x8;
3056 break;
3057 case glslang::EOpPackUnorm4x8:
3058 libCall = spv::GLSLstd450PackUnorm4x8;
3059 break;
3060 case glslang::EOpUnpackUnorm4x8:
3061 libCall = spv::GLSLstd450UnpackUnorm4x8;
3062 break;
3063 case glslang::EOpPackDouble2x32:
3064 libCall = spv::GLSLstd450PackDouble2x32;
3065 break;
3066 case glslang::EOpUnpackDouble2x32:
3067 libCall = spv::GLSLstd450UnpackDouble2x32;
3068 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003069
3070 case glslang::EOpDPdx:
3071 unaryOp = spv::OpDPdx;
3072 break;
3073 case glslang::EOpDPdy:
3074 unaryOp = spv::OpDPdy;
3075 break;
3076 case glslang::EOpFwidth:
3077 unaryOp = spv::OpFwidth;
3078 break;
3079 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003080 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003081 unaryOp = spv::OpDPdxFine;
3082 break;
3083 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003084 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003085 unaryOp = spv::OpDPdyFine;
3086 break;
3087 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003088 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003089 unaryOp = spv::OpFwidthFine;
3090 break;
3091 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003092 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003093 unaryOp = spv::OpDPdxCoarse;
3094 break;
3095 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003096 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003097 unaryOp = spv::OpDPdyCoarse;
3098 break;
3099 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003100 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003101 unaryOp = spv::OpFwidthCoarse;
3102 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003103 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003104 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003105 libCall = spv::GLSLstd450InterpolateAtCentroid;
3106 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003107 case glslang::EOpAny:
3108 unaryOp = spv::OpAny;
3109 break;
3110 case glslang::EOpAll:
3111 unaryOp = spv::OpAll;
3112 break;
3113
3114 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003115 if (isFloat)
3116 libCall = spv::GLSLstd450FAbs;
3117 else
3118 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003119 break;
3120 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003121 if (isFloat)
3122 libCall = spv::GLSLstd450FSign;
3123 else
3124 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003125 break;
3126
John Kessenichfc51d282015-08-19 13:34:18 -06003127 case glslang::EOpAtomicCounterIncrement:
3128 case glslang::EOpAtomicCounterDecrement:
3129 case glslang::EOpAtomicCounter:
3130 {
3131 // Handle all of the atomics in one place, in createAtomicOperation()
3132 std::vector<spv::Id> operands;
3133 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003134 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003135 }
3136
John Kessenichfc51d282015-08-19 13:34:18 -06003137 case glslang::EOpBitFieldReverse:
3138 unaryOp = spv::OpBitReverse;
3139 break;
3140 case glslang::EOpBitCount:
3141 unaryOp = spv::OpBitCount;
3142 break;
3143 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003144 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003145 break;
3146 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003147 if (isUnsigned)
3148 libCall = spv::GLSLstd450FindUMsb;
3149 else
3150 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003151 break;
3152
John Kessenich140f3df2015-06-26 16:58:36 -06003153 default:
3154 return 0;
3155 }
3156
3157 spv::Id id;
3158 if (libCall >= 0) {
3159 std::vector<spv::Id> args;
3160 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003161 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003162 } else
3163 id = builder.createUnaryOp(unaryOp, typeId, operand);
3164
John Kessenich32cfd492016-02-02 12:37:46 -07003165 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003166}
3167
John Kessenich7a53f762016-01-20 11:19:27 -07003168// Create a unary operation on a matrix
3169spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3170{
3171 // Handle unary operations vector by vector.
3172 // The result type is the same type as the original type.
3173 // The algorithm is to:
3174 // - break the matrix into vectors
3175 // - apply the operation to each vector
3176 // - make a matrix out the vector results
3177
3178 // get the types sorted out
3179 int numCols = builder.getNumColumns(operand);
3180 int numRows = builder.getNumRows(operand);
3181 spv::Id scalarType = builder.getScalarTypeId(typeId);
3182 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3183 std::vector<spv::Id> results;
3184
3185 // do each vector op
3186 for (int c = 0; c < numCols; ++c) {
3187 std::vector<unsigned int> indexes;
3188 indexes.push_back(c);
3189 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3190 results.push_back(builder.createUnaryOp(op, vecType, vec));
3191 builder.setPrecision(results.back(), precision);
3192 }
3193
3194 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003195 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003196}
3197
John Kessenich140f3df2015-06-26 16:58:36 -06003198spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3199{
3200 spv::Op convOp = spv::OpNop;
3201 spv::Id zero = 0;
3202 spv::Id one = 0;
3203
3204 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3205
3206 switch (op) {
3207 case glslang::EOpConvIntToBool:
3208 case glslang::EOpConvUintToBool:
3209 zero = builder.makeUintConstant(0);
3210 zero = makeSmearedConstant(zero, vectorSize);
3211 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3212
3213 case glslang::EOpConvFloatToBool:
3214 zero = builder.makeFloatConstant(0.0F);
3215 zero = makeSmearedConstant(zero, vectorSize);
3216 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3217
3218 case glslang::EOpConvDoubleToBool:
3219 zero = builder.makeDoubleConstant(0.0);
3220 zero = makeSmearedConstant(zero, vectorSize);
3221 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3222
3223 case glslang::EOpConvBoolToFloat:
3224 convOp = spv::OpSelect;
3225 zero = builder.makeFloatConstant(0.0);
3226 one = builder.makeFloatConstant(1.0);
3227 break;
3228 case glslang::EOpConvBoolToDouble:
3229 convOp = spv::OpSelect;
3230 zero = builder.makeDoubleConstant(0.0);
3231 one = builder.makeDoubleConstant(1.0);
3232 break;
3233 case glslang::EOpConvBoolToInt:
3234 zero = builder.makeIntConstant(0);
3235 one = builder.makeIntConstant(1);
3236 convOp = spv::OpSelect;
3237 break;
3238 case glslang::EOpConvBoolToUint:
3239 zero = builder.makeUintConstant(0);
3240 one = builder.makeUintConstant(1);
3241 convOp = spv::OpSelect;
3242 break;
3243
3244 case glslang::EOpConvIntToFloat:
3245 case glslang::EOpConvIntToDouble:
3246 convOp = spv::OpConvertSToF;
3247 break;
3248
3249 case glslang::EOpConvUintToFloat:
3250 case glslang::EOpConvUintToDouble:
3251 convOp = spv::OpConvertUToF;
3252 break;
3253
3254 case glslang::EOpConvDoubleToFloat:
3255 case glslang::EOpConvFloatToDouble:
3256 convOp = spv::OpFConvert;
3257 break;
3258
3259 case glslang::EOpConvFloatToInt:
3260 case glslang::EOpConvDoubleToInt:
3261 convOp = spv::OpConvertFToS;
3262 break;
3263
3264 case glslang::EOpConvUintToInt:
3265 case glslang::EOpConvIntToUint:
3266 convOp = spv::OpBitcast;
3267 break;
3268
3269 case glslang::EOpConvFloatToUint:
3270 case glslang::EOpConvDoubleToUint:
3271 convOp = spv::OpConvertFToU;
3272 break;
3273 default:
3274 break;
3275 }
3276
3277 spv::Id result = 0;
3278 if (convOp == spv::OpNop)
3279 return result;
3280
3281 if (convOp == spv::OpSelect) {
3282 zero = makeSmearedConstant(zero, vectorSize);
3283 one = makeSmearedConstant(one, vectorSize);
3284 result = builder.createTriOp(convOp, destType, operand, one, zero);
3285 } else
3286 result = builder.createUnaryOp(convOp, destType, operand);
3287
John Kessenich32cfd492016-02-02 12:37:46 -07003288 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003289}
3290
3291spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3292{
3293 if (vectorSize == 0)
3294 return constant;
3295
3296 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3297 std::vector<spv::Id> components;
3298 for (int c = 0; c < vectorSize; ++c)
3299 components.push_back(constant);
3300 return builder.makeCompositeConstant(vectorTypeId, components);
3301}
3302
John Kessenich426394d2015-07-23 10:22:48 -06003303// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003304spv::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 -06003305{
3306 spv::Op opCode = spv::OpNop;
3307
3308 switch (op) {
3309 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003310 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003311 opCode = spv::OpAtomicIAdd;
3312 break;
3313 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003314 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003315 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003316 break;
3317 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003318 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003319 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003320 break;
3321 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003322 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003323 opCode = spv::OpAtomicAnd;
3324 break;
3325 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003326 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003327 opCode = spv::OpAtomicOr;
3328 break;
3329 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003330 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003331 opCode = spv::OpAtomicXor;
3332 break;
3333 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003334 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003335 opCode = spv::OpAtomicExchange;
3336 break;
3337 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003338 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003339 opCode = spv::OpAtomicCompareExchange;
3340 break;
3341 case glslang::EOpAtomicCounterIncrement:
3342 opCode = spv::OpAtomicIIncrement;
3343 break;
3344 case glslang::EOpAtomicCounterDecrement:
3345 opCode = spv::OpAtomicIDecrement;
3346 break;
3347 case glslang::EOpAtomicCounter:
3348 opCode = spv::OpAtomicLoad;
3349 break;
3350 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003351 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003352 break;
3353 }
3354
3355 // Sort out the operands
3356 // - mapping from glslang -> SPV
3357 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003358 // - compare-exchange swaps the value and comparator
3359 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003360 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3361 auto opIt = operands.begin(); // walk the glslang operands
3362 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003363 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3364 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3365 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003366 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3367 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003368 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003369 spvAtomicOperands.push_back(*(opIt + 1));
3370 spvAtomicOperands.push_back(*opIt);
3371 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003372 }
John Kessenich426394d2015-07-23 10:22:48 -06003373
John Kessenich3e60a6f2015-09-14 22:45:16 -06003374 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003375 for (; opIt != operands.end(); ++opIt)
3376 spvAtomicOperands.push_back(*opIt);
3377
3378 return builder.createOp(opCode, typeId, spvAtomicOperands);
3379}
3380
John Kessenich5e4b1242015-08-06 22:53:06 -06003381spv::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 -06003382{
John Kessenich5e4b1242015-08-06 22:53:06 -06003383 bool isUnsigned = typeProxy == glslang::EbtUint;
3384 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3385
John Kessenich140f3df2015-06-26 16:58:36 -06003386 spv::Op opCode = spv::OpNop;
3387 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003388 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003389 spv::Id typeId0 = 0;
3390 if (consumedOperands > 0)
3391 typeId0 = builder.getTypeId(operands[0]);
3392 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003393
3394 switch (op) {
3395 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003396 if (isFloat)
3397 libCall = spv::GLSLstd450FMin;
3398 else if (isUnsigned)
3399 libCall = spv::GLSLstd450UMin;
3400 else
3401 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003402 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003403 break;
3404 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003405 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003406 break;
3407 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003408 if (isFloat)
3409 libCall = spv::GLSLstd450FMax;
3410 else if (isUnsigned)
3411 libCall = spv::GLSLstd450UMax;
3412 else
3413 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003414 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003415 break;
3416 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003417 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003418 break;
3419 case glslang::EOpDot:
3420 opCode = spv::OpDot;
3421 break;
3422 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003423 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003424 break;
3425
3426 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003427 if (isFloat)
3428 libCall = spv::GLSLstd450FClamp;
3429 else if (isUnsigned)
3430 libCall = spv::GLSLstd450UClamp;
3431 else
3432 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003433 builder.promoteScalar(precision, operands.front(), operands[1]);
3434 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003435 break;
3436 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003437 if (isFloat)
3438 libCall = spv::GLSLstd450FMix;
John Kessenich6c292d32016-02-15 20:58:50 -07003439 else {
3440 opCode = spv::OpSelect;
3441 spv::MissingFunctionality("translating integer mix to OpSelect");
3442 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003443 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003444 break;
3445 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003446 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003447 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003448 break;
3449 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003450 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003451 builder.promoteScalar(precision, operands[0], operands[2]);
3452 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003453 break;
3454
3455 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003456 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003457 break;
3458 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003459 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003460 break;
3461 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003462 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003463 break;
3464 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003465 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003466 break;
3467 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003468 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003469 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003470 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003471 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003472 libCall = spv::GLSLstd450InterpolateAtSample;
3473 break;
3474 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003475 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003476 libCall = spv::GLSLstd450InterpolateAtOffset;
3477 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003478 case glslang::EOpAddCarry:
3479 opCode = spv::OpIAddCarry;
3480 typeId = builder.makeStructResultType(typeId0, typeId0);
3481 consumedOperands = 2;
3482 break;
3483 case glslang::EOpSubBorrow:
3484 opCode = spv::OpISubBorrow;
3485 typeId = builder.makeStructResultType(typeId0, typeId0);
3486 consumedOperands = 2;
3487 break;
3488 case glslang::EOpUMulExtended:
3489 opCode = spv::OpUMulExtended;
3490 typeId = builder.makeStructResultType(typeId0, typeId0);
3491 consumedOperands = 2;
3492 break;
3493 case glslang::EOpIMulExtended:
3494 opCode = spv::OpSMulExtended;
3495 typeId = builder.makeStructResultType(typeId0, typeId0);
3496 consumedOperands = 2;
3497 break;
3498 case glslang::EOpBitfieldExtract:
3499 if (isUnsigned)
3500 opCode = spv::OpBitFieldUExtract;
3501 else
3502 opCode = spv::OpBitFieldSExtract;
3503 break;
3504 case glslang::EOpBitfieldInsert:
3505 opCode = spv::OpBitFieldInsert;
3506 break;
3507
3508 case glslang::EOpFma:
3509 libCall = spv::GLSLstd450Fma;
3510 break;
3511 case glslang::EOpFrexp:
3512 libCall = spv::GLSLstd450FrexpStruct;
3513 if (builder.getNumComponents(operands[0]) == 1)
3514 frexpIntType = builder.makeIntegerType(32, true);
3515 else
3516 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3517 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3518 consumedOperands = 1;
3519 break;
3520 case glslang::EOpLdexp:
3521 libCall = spv::GLSLstd450Ldexp;
3522 break;
3523
John Kessenich140f3df2015-06-26 16:58:36 -06003524 default:
3525 return 0;
3526 }
3527
3528 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003529 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003530 // Use an extended instruction from the standard library.
3531 // Construct the call arguments, without modifying the original operands vector.
3532 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3533 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003534 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003535 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003536 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003537 case 0:
3538 // should all be handled by visitAggregate and createNoArgOperation
3539 assert(0);
3540 return 0;
3541 case 1:
3542 // should all be handled by createUnaryOperation
3543 assert(0);
3544 return 0;
3545 case 2:
3546 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3547 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003548 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003549 // anything 3 or over doesn't have l-value operands, so all should be consumed
3550 assert(consumedOperands == operands.size());
3551 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003552 break;
3553 }
3554 }
3555
John Kessenich55e7d112015-11-15 21:33:39 -07003556 // Decode the return types that were structures
3557 switch (op) {
3558 case glslang::EOpAddCarry:
3559 case glslang::EOpSubBorrow:
3560 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3561 id = builder.createCompositeExtract(id, typeId0, 0);
3562 break;
3563 case glslang::EOpUMulExtended:
3564 case glslang::EOpIMulExtended:
3565 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3566 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3567 break;
3568 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003569 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003570 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3571 id = builder.createCompositeExtract(id, typeId0, 0);
3572 break;
3573 default:
3574 break;
3575 }
3576
John Kessenich32cfd492016-02-02 12:37:46 -07003577 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003578}
3579
3580// Intrinsics with no arguments, no return value, and no precision.
3581spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3582{
3583 // TODO: get the barrier operands correct
3584
3585 switch (op) {
3586 case glslang::EOpEmitVertex:
3587 builder.createNoResultOp(spv::OpEmitVertex);
3588 return 0;
3589 case glslang::EOpEndPrimitive:
3590 builder.createNoResultOp(spv::OpEndPrimitive);
3591 return 0;
3592 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003593 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3594 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003595 return 0;
3596 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003597 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003598 return 0;
3599 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003600 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003601 return 0;
3602 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003603 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003604 return 0;
3605 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003606 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003607 return 0;
3608 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003609 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003610 return 0;
3611 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003612 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003613 return 0;
3614 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003615 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003616 return 0;
3617 }
3618}
3619
3620spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3621{
John Kessenich2f273362015-07-18 22:34:27 -06003622 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003623 spv::Id id;
3624 if (symbolValues.end() != iter) {
3625 id = iter->second;
3626 return id;
3627 }
3628
3629 // it was not found, create it
3630 id = createSpvVariable(symbol);
3631 symbolValues[symbol->getId()] = id;
3632
3633 if (! symbol->getType().isStruct()) {
3634 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003635 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003636 if (symbol->getType().getQualifier().hasSpecConstantId())
3637 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003638 if (symbol->getQualifier().hasLocation())
3639 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3640 if (symbol->getQualifier().hasIndex())
3641 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3642 if (symbol->getQualifier().hasComponent())
3643 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3644 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003645 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003646 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003647 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003648 if (symbol->getQualifier().hasXfbBuffer())
3649 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3650 if (symbol->getQualifier().hasXfbOffset())
3651 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3652 }
3653 }
3654
John Kesseniche0b6cad2015-12-24 10:30:13 -07003655 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003656 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003657 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003658 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003659 }
John Kessenich140f3df2015-06-26 16:58:36 -06003660 if (symbol->getQualifier().hasSet())
3661 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003662 else if (IsDescriptorResource(symbol->getType())) {
3663 // default to 0
3664 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3665 }
John Kessenich140f3df2015-06-26 16:58:36 -06003666 if (symbol->getQualifier().hasBinding())
3667 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003668 if (symbol->getQualifier().hasAttachment())
3669 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003670 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003671 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003672 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003673 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003674 if (symbol->getQualifier().hasXfbBuffer())
3675 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3676 }
3677
Rex Xu1da878f2016-02-21 20:59:01 +08003678 if (symbol->getType().isImage()) {
3679 std::vector<spv::Decoration> memory;
3680 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3681 for (unsigned int i = 0; i < memory.size(); ++i)
3682 addDecoration(id, memory[i]);
3683 }
3684
John Kessenich140f3df2015-06-26 16:58:36 -06003685 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003686 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003687 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003688 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003689
John Kessenich140f3df2015-06-26 16:58:36 -06003690 return id;
3691}
3692
John Kessenich55e7d112015-11-15 21:33:39 -07003693// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003694void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3695{
3696 if (dec != spv::BadValue)
3697 builder.addDecoration(id, dec);
3698}
3699
John Kessenich55e7d112015-11-15 21:33:39 -07003700// If 'dec' is valid, add a one-operand decoration to an object
3701void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3702{
3703 if (dec != spv::BadValue)
3704 builder.addDecoration(id, dec, value);
3705}
3706
3707// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003708void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3709{
3710 if (dec != spv::BadValue)
3711 builder.addMemberDecoration(id, (unsigned)member, dec);
3712}
3713
John Kessenich92187592016-02-01 13:45:25 -07003714// If 'dec' is valid, add a one-operand decoration to a struct member
3715void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3716{
3717 if (dec != spv::BadValue)
3718 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3719}
3720
John Kessenich55e7d112015-11-15 21:33:39 -07003721// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003722// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003723//
3724// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3725//
3726// Recursively walk the nodes. The nodes form a tree whose leaves are
3727// regular constants, which themselves are trees that createSpvConstant()
3728// recursively walks. So, this function walks the "top" of the tree:
3729// - emit specialization constant-building instructions for specConstant
3730// - when running into a non-spec-constant, switch to createSpvConstant()
3731spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3732{
3733 assert(node.getQualifier().storage == glslang::EvqConst);
3734
John Kessenich6c292d32016-02-15 20:58:50 -07003735 if (! node.getQualifier().specConstant) {
3736 // hand off to the non-spec-constant path
3737 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3738 int nextConst = 0;
3739 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3740 nextConst, false);
3741 }
3742
3743 // We now know we have a specialization constant to build
3744
3745 if (node.getAsSymbolNode() && node.getQualifier().hasSpecConstantId()) {
3746 // this is a direct literal assigned to a layout(constant_id=) declaration
3747 int nextConst = 0;
3748 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3749 nextConst, true);
3750 } else {
3751 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3752 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3753 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3754 std::vector<spv::Id> dimConstId;
3755 for (int dim = 0; dim < 3; ++dim) {
3756 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3757 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3758 if (specConst)
3759 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3760 }
3761 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3762 } else {
3763 spv::MissingFunctionality("specialization-constant expression trees");
3764 return spv::NoResult;
3765 }
3766 }
John Kessenich55e7d112015-11-15 21:33:39 -07003767}
3768
John Kessenich140f3df2015-06-26 16:58:36 -06003769// Use 'consts' as the flattened glslang source of scalar constants to recursively
3770// build the aggregate SPIR-V constant.
3771//
3772// If there are not enough elements present in 'consts', 0 will be substituted;
3773// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3774//
John Kessenich55e7d112015-11-15 21:33:39 -07003775spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003776{
3777 // vector of constants for SPIR-V
3778 std::vector<spv::Id> spvConsts;
3779
3780 // Type is used for struct and array constants
3781 spv::Id typeId = convertGlslangToSpvType(glslangType);
3782
3783 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003784 glslang::TType elementType(glslangType, 0);
3785 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003786 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003787 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003788 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003789 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003790 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003791 } else if (glslangType.getStruct()) {
3792 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3793 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003794 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003795 } else if (glslangType.isVector()) {
3796 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3797 bool zero = nextConst >= consts.size();
3798 switch (glslangType.getBasicType()) {
3799 case glslang::EbtInt:
3800 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3801 break;
3802 case glslang::EbtUint:
3803 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3804 break;
3805 case glslang::EbtFloat:
3806 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3807 break;
3808 case glslang::EbtDouble:
3809 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3810 break;
3811 case glslang::EbtBool:
3812 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3813 break;
3814 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003815 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003816 break;
3817 }
3818 ++nextConst;
3819 }
3820 } else {
3821 // we have a non-aggregate (scalar) constant
3822 bool zero = nextConst >= consts.size();
3823 spv::Id scalar = 0;
3824 switch (glslangType.getBasicType()) {
3825 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003826 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003827 break;
3828 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003829 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003830 break;
3831 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003832 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003833 break;
3834 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003835 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003836 break;
3837 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003838 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003839 break;
3840 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003841 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003842 break;
3843 }
3844 ++nextConst;
3845 return scalar;
3846 }
3847
3848 return builder.makeCompositeConstant(typeId, spvConsts);
3849}
3850
John Kessenich7c1aa102015-10-15 13:29:11 -06003851// Return true if the node is a constant or symbol whose reading has no
3852// non-trivial observable cost or effect.
3853bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3854{
3855 // don't know what this is
3856 if (node == nullptr)
3857 return false;
3858
3859 // a constant is safe
3860 if (node->getAsConstantUnion() != nullptr)
3861 return true;
3862
3863 // not a symbol means non-trivial
3864 if (node->getAsSymbolNode() == nullptr)
3865 return false;
3866
3867 // a symbol, depends on what's being read
3868 switch (node->getType().getQualifier().storage) {
3869 case glslang::EvqTemporary:
3870 case glslang::EvqGlobal:
3871 case glslang::EvqIn:
3872 case glslang::EvqInOut:
3873 case glslang::EvqConst:
3874 case glslang::EvqConstReadOnly:
3875 case glslang::EvqUniform:
3876 return true;
3877 default:
3878 return false;
3879 }
3880}
3881
3882// A node is trivial if it is a single operation with no side effects.
3883// Error on the side of saying non-trivial.
3884// Return true if trivial.
3885bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3886{
3887 if (node == nullptr)
3888 return false;
3889
3890 // symbols and constants are trivial
3891 if (isTrivialLeaf(node))
3892 return true;
3893
3894 // otherwise, it needs to be a simple operation or one or two leaf nodes
3895
3896 // not a simple operation
3897 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3898 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3899 if (binaryNode == nullptr && unaryNode == nullptr)
3900 return false;
3901
3902 // not on leaf nodes
3903 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3904 return false;
3905
3906 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3907 return false;
3908 }
3909
3910 switch (node->getAsOperator()->getOp()) {
3911 case glslang::EOpLogicalNot:
3912 case glslang::EOpConvIntToBool:
3913 case glslang::EOpConvUintToBool:
3914 case glslang::EOpConvFloatToBool:
3915 case glslang::EOpConvDoubleToBool:
3916 case glslang::EOpEqual:
3917 case glslang::EOpNotEqual:
3918 case glslang::EOpLessThan:
3919 case glslang::EOpGreaterThan:
3920 case glslang::EOpLessThanEqual:
3921 case glslang::EOpGreaterThanEqual:
3922 case glslang::EOpIndexDirect:
3923 case glslang::EOpIndexDirectStruct:
3924 case glslang::EOpLogicalXor:
3925 case glslang::EOpAny:
3926 case glslang::EOpAll:
3927 return true;
3928 default:
3929 return false;
3930 }
3931}
3932
3933// Emit short-circuiting code, where 'right' is never evaluated unless
3934// the left side is true (for &&) or false (for ||).
3935spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3936{
3937 spv::Id boolTypeId = builder.makeBoolType();
3938
3939 // emit left operand
3940 builder.clearAccessChain();
3941 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08003942 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06003943
3944 // Operands to accumulate OpPhi operands
3945 std::vector<spv::Id> phiOperands;
3946 // accumulate left operand's phi information
3947 phiOperands.push_back(leftId);
3948 phiOperands.push_back(builder.getBuildPoint()->getId());
3949
3950 // Make the two kinds of operation symmetric with a "!"
3951 // || => emit "if (! left) result = right"
3952 // && => emit "if ( left) result = right"
3953 //
3954 // TODO: this runtime "not" for || could be avoided by adding functionality
3955 // to 'builder' to have an "else" without an "then"
3956 if (op == glslang::EOpLogicalOr)
3957 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3958
3959 // make an "if" based on the left value
3960 spv::Builder::If ifBuilder(leftId, builder);
3961
3962 // emit right operand as the "then" part of the "if"
3963 builder.clearAccessChain();
3964 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08003965 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06003966
3967 // accumulate left operand's phi information
3968 phiOperands.push_back(rightId);
3969 phiOperands.push_back(builder.getBuildPoint()->getId());
3970
3971 // finish the "if"
3972 ifBuilder.makeEndIf();
3973
3974 // phi together the two results
3975 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3976}
3977
John Kessenich140f3df2015-06-26 16:58:36 -06003978}; // end anonymous namespace
3979
3980namespace glslang {
3981
John Kessenich68d78fd2015-07-12 19:28:10 -06003982void GetSpirvVersion(std::string& version)
3983{
John Kessenich9e55f632015-07-15 10:03:39 -06003984 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003985 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003986 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003987 version = buf;
3988}
3989
John Kessenich140f3df2015-06-26 16:58:36 -06003990// Write SPIR-V out to a binary file
3991void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3992{
3993 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003994 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003995 for (int i = 0; i < (int)spirv.size(); ++i) {
3996 unsigned int word = spirv[i];
3997 out.write((const char*)&word, 4);
3998 }
3999 out.close();
4000}
4001
4002//
4003// Set up the glslang traversal
4004//
4005void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4006{
4007 TIntermNode* root = intermediate.getTreeRoot();
4008
4009 if (root == 0)
4010 return;
4011
4012 glslang::GetThreadPoolAllocator().push();
4013
4014 TGlslangToSpvTraverser it(&intermediate);
4015
4016 root->traverse(&it);
4017
4018 it.dumpSpv(spirv);
4019
4020 glslang::GetThreadPoolAllocator().pop();
4021}
4022
4023}; // end namespace glslang