blob: 7a7baa2b25c9aaec486f28d1bbb7c84dd9426474 [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);
John Kessenich4d65ee32016-03-12 18:17:47 -0700593 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
594 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
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
qiningda397332016-03-09 19:54:03 -0500722 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700723 builder.dump(out);
724}
725
John Kessenich140f3df2015-06-26 16:58:36 -0600726TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
727{
728 if (! mainTerminated) {
729 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
730 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600731 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600732 }
733}
734
735//
736// Implement the traversal functions.
737//
738// Return true from interior nodes to have the external traversal
739// continue on to children. Return false if children were
740// already processed.
741//
742
743//
744// Symbols can turn into
745// - uniform/input reads
746// - output writes
747// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
748// - something simple that degenerates into the last bullet
749//
750void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
751{
752 // getSymbolId() will set up all the IO decorations on the first call.
753 // Formal function parameters were mapped during makeFunctions().
754 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700755
756 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
757 if (builder.isPointer(id)) {
758 spv::StorageClass sc = builder.getStorageClass(id);
759 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
760 iOSet.insert(id);
761 }
762
763 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700764 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600765 // Prepare to generate code for the access
766
767 // L-value chains will be computed left to right. We're on the symbol now,
768 // which is the left-most part of the access chain, so now is "clear" time,
769 // followed by setting the base.
770 builder.clearAccessChain();
771
772 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700773 // except for
774 // A) "const in" arguments to a function, which are an intermediate object.
775 // See comments in handleUserFunctionCall().
776 // B) Specialization constants (normal constant don't even come in as a variable),
777 // These are also pure R-values.
778 glslang::TQualifier qualifier = symbol->getQualifier();
779 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
780 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600781 builder.setAccessChainRValue(id);
782 else
783 builder.setAccessChainLValue(id);
784 }
785}
786
787bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
788{
789 // First, handle special cases
790 switch (node->getOp()) {
791 case glslang::EOpAssign:
792 case glslang::EOpAddAssign:
793 case glslang::EOpSubAssign:
794 case glslang::EOpMulAssign:
795 case glslang::EOpVectorTimesMatrixAssign:
796 case glslang::EOpVectorTimesScalarAssign:
797 case glslang::EOpMatrixTimesScalarAssign:
798 case glslang::EOpMatrixTimesMatrixAssign:
799 case glslang::EOpDivAssign:
800 case glslang::EOpModAssign:
801 case glslang::EOpAndAssign:
802 case glslang::EOpInclusiveOrAssign:
803 case glslang::EOpExclusiveOrAssign:
804 case glslang::EOpLeftShiftAssign:
805 case glslang::EOpRightShiftAssign:
806 // A bin-op assign "a += b" means the same thing as "a = a + b"
807 // where a is evaluated before b. For a simple assignment, GLSL
808 // says to evaluate the left before the right. So, always, left
809 // node then right node.
810 {
811 // get the left l-value, save it away
812 builder.clearAccessChain();
813 node->getLeft()->traverse(this);
814 spv::Builder::AccessChain lValue = builder.getAccessChain();
815
816 // evaluate the right
817 builder.clearAccessChain();
818 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700819 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600820
821 if (node->getOp() != glslang::EOpAssign) {
822 // the left is also an r-value
823 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700824 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600825
826 // do the operation
827 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
828 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
829 node->getType().getBasicType());
830
831 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700832 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600833 }
834
835 // store the result
836 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800837 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600838
839 // assignments are expressions having an rValue after they are evaluated...
840 builder.clearAccessChain();
841 builder.setAccessChainRValue(rValue);
842 }
843 return false;
844 case glslang::EOpIndexDirect:
845 case glslang::EOpIndexDirectStruct:
846 {
847 // Get the left part of the access chain.
848 node->getLeft()->traverse(this);
849
850 // Add the next element in the chain
851
John Kessenich55e7d112015-11-15 21:33:39 -0700852 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600853 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
854 // This may be, e.g., an anonymous block-member selection, which generally need
855 // index remapping due to hidden members in anonymous blocks.
856 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700857 assert(remapper.size() > 0);
858 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600859 }
860
861 if (! node->getLeft()->getType().isArray() &&
862 node->getLeft()->getType().isVector() &&
863 node->getOp() == glslang::EOpIndexDirect) {
864 // This is essentially a hard-coded vector swizzle of size 1,
865 // so short circuit the access-chain stuff with a swizzle.
866 std::vector<unsigned> swizzle;
867 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600868 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600869 } else {
870 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600871 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600872 }
873 }
874 return false;
875 case glslang::EOpIndexIndirect:
876 {
877 // Structure or array or vector indirection.
878 // Will use native SPIR-V access-chain for struct and array indirection;
879 // matrices are arrays of vectors, so will also work for a matrix.
880 // Will use the access chain's 'component' for variable index into a vector.
881
882 // This adapter is building access chains left to right.
883 // Set up the access chain to the left.
884 node->getLeft()->traverse(this);
885
886 // save it so that computing the right side doesn't trash it
887 spv::Builder::AccessChain partial = builder.getAccessChain();
888
889 // compute the next index in the chain
890 builder.clearAccessChain();
891 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700892 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600893
894 // restore the saved access chain
895 builder.setAccessChain(partial);
896
897 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600898 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600899 else
John Kessenichfa668da2015-09-13 14:46:30 -0600900 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600901 }
902 return false;
903 case glslang::EOpVectorSwizzle:
904 {
905 node->getLeft()->traverse(this);
906 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
907 std::vector<unsigned> swizzle;
908 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
909 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600910 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600911 }
912 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600913 case glslang::EOpLogicalOr:
914 case glslang::EOpLogicalAnd:
915 {
916
917 // These may require short circuiting, but can sometimes be done as straight
918 // binary operations. The right operand must be short circuited if it has
919 // side effects, and should probably be if it is complex.
920 if (isTrivial(node->getRight()->getAsTyped()))
921 break; // handle below as a normal binary operation
922 // otherwise, we need to do dynamic short circuiting on the right operand
923 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
924 builder.clearAccessChain();
925 builder.setAccessChainRValue(result);
926 }
927 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600928 default:
929 break;
930 }
931
932 // Assume generic binary op...
933
John Kessenich32cfd492016-02-02 12:37:46 -0700934 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600935 builder.clearAccessChain();
936 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700937 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600938
John Kessenich32cfd492016-02-02 12:37:46 -0700939 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600940 builder.clearAccessChain();
941 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700942 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600943
John Kessenich32cfd492016-02-02 12:37:46 -0700944 // get result
945 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
946 convertGlslangToSpvType(node->getType()), left, right,
947 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600948
John Kessenich50e57562015-12-21 21:21:11 -0700949 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600950 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700951 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700952 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600953 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600954 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600955 return false;
956 }
John Kessenich140f3df2015-06-26 16:58:36 -0600957}
958
959bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
960{
John Kessenichfc51d282015-08-19 13:34:18 -0600961 spv::Id result = spv::NoResult;
962
963 // try texturing first
964 result = createImageTextureFunctionCall(node);
965 if (result != spv::NoResult) {
966 builder.clearAccessChain();
967 builder.setAccessChainRValue(result);
968
969 return false; // done with this node
970 }
971
972 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600973
974 if (node->getOp() == glslang::EOpArrayLength) {
975 // Quite special; won't want to evaluate the operand.
976
977 // Normal .length() would have been constant folded by the front-end.
978 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600979 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600980 assert(node->getOperand()->getType().isRuntimeSizedArray());
981 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
982 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600983 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
984 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600985
986 builder.clearAccessChain();
987 builder.setAccessChainRValue(length);
988
989 return false;
990 }
991
John Kessenichfc51d282015-08-19 13:34:18 -0600992 // Start by evaluating the operand
993
John Kessenich140f3df2015-06-26 16:58:36 -0600994 builder.clearAccessChain();
995 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800996
Rex Xufc618912015-09-09 16:42:49 +0800997 spv::Id operand = spv::NoResult;
998
999 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1000 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001001 node->getOp() == glslang::EOpAtomicCounter ||
1002 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001003 operand = builder.accessChainGetLValue(); // Special case l-value operands
1004 else
John Kessenich32cfd492016-02-02 12:37:46 -07001005 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001006
1007 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1008
1009 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001010 if (! result)
1011 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -06001012
1013 // if not, then possibly an operation
1014 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -07001015 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001016
1017 if (result) {
1018 builder.clearAccessChain();
1019 builder.setAccessChainRValue(result);
1020
1021 return false; // done with this node
1022 }
1023
1024 // it must be a special case, check...
1025 switch (node->getOp()) {
1026 case glslang::EOpPostIncrement:
1027 case glslang::EOpPostDecrement:
1028 case glslang::EOpPreIncrement:
1029 case glslang::EOpPreDecrement:
1030 {
1031 // we need the integer value "1" or the floating point "1.0" to add/subtract
1032 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
1033 builder.makeFloatConstant(1.0F) :
1034 builder.makeIntConstant(1);
1035 glslang::TOperator op;
1036 if (node->getOp() == glslang::EOpPreIncrement ||
1037 node->getOp() == glslang::EOpPostIncrement)
1038 op = glslang::EOpAdd;
1039 else
1040 op = glslang::EOpSub;
1041
1042 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1043 convertGlslangToSpvType(node->getType()), operand, one,
1044 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001045 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001046
1047 // The result of operation is always stored, but conditionally the
1048 // consumed result. The consumed result is always an r-value.
1049 builder.accessChainStore(result);
1050 builder.clearAccessChain();
1051 if (node->getOp() == glslang::EOpPreIncrement ||
1052 node->getOp() == glslang::EOpPreDecrement)
1053 builder.setAccessChainRValue(result);
1054 else
1055 builder.setAccessChainRValue(operand);
1056 }
1057
1058 return false;
1059
1060 case glslang::EOpEmitStreamVertex:
1061 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1062 return false;
1063 case glslang::EOpEndStreamPrimitive:
1064 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1065 return false;
1066
1067 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001068 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001069 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001070 }
John Kessenich140f3df2015-06-26 16:58:36 -06001071}
1072
1073bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1074{
John Kessenichfc51d282015-08-19 13:34:18 -06001075 spv::Id result = spv::NoResult;
1076
1077 // try texturing
1078 result = createImageTextureFunctionCall(node);
1079 if (result != spv::NoResult) {
1080 builder.clearAccessChain();
1081 builder.setAccessChainRValue(result);
1082
1083 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001084 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001085 // "imageStore" is a special case, which has no result
1086 return false;
1087 }
John Kessenichfc51d282015-08-19 13:34:18 -06001088
John Kessenich140f3df2015-06-26 16:58:36 -06001089 glslang::TOperator binOp = glslang::EOpNull;
1090 bool reduceComparison = true;
1091 bool isMatrix = false;
1092 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001093 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001094
1095 assert(node->getOp());
1096
1097 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1098
1099 switch (node->getOp()) {
1100 case glslang::EOpSequence:
1101 {
1102 if (preVisit)
1103 ++sequenceDepth;
1104 else
1105 --sequenceDepth;
1106
1107 if (sequenceDepth == 1) {
1108 // If this is the parent node of all the functions, we want to see them
1109 // early, so all call points have actual SPIR-V functions to reference.
1110 // In all cases, still let the traverser visit the children for us.
1111 makeFunctions(node->getAsAggregate()->getSequence());
1112
1113 // Also, we want all globals initializers to go into the entry of main(), before
1114 // anything else gets there, so visit out of order, doing them all now.
1115 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1116
1117 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1118 // so do them manually.
1119 visitFunctions(node->getAsAggregate()->getSequence());
1120
1121 return false;
1122 }
1123
1124 return true;
1125 }
1126 case glslang::EOpLinkerObjects:
1127 {
1128 if (visit == glslang::EvPreVisit)
1129 linkageOnly = true;
1130 else
1131 linkageOnly = false;
1132
1133 return true;
1134 }
1135 case glslang::EOpComma:
1136 {
1137 // processing from left to right naturally leaves the right-most
1138 // lying around in the access chain
1139 glslang::TIntermSequence& glslangOperands = node->getSequence();
1140 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1141 glslangOperands[i]->traverse(this);
1142
1143 return false;
1144 }
1145 case glslang::EOpFunction:
1146 if (visit == glslang::EvPreVisit) {
1147 if (isShaderEntrypoint(node)) {
1148 inMain = true;
1149 builder.setBuildPoint(shaderEntry->getLastBlock());
1150 } else {
1151 handleFunctionEntry(node);
1152 }
1153 } else {
1154 if (inMain)
1155 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001156 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001157 inMain = false;
1158 }
1159
1160 return true;
1161 case glslang::EOpParameters:
1162 // Parameters will have been consumed by EOpFunction processing, but not
1163 // the body, so we still visited the function node's children, making this
1164 // child redundant.
1165 return false;
1166 case glslang::EOpFunctionCall:
1167 {
1168 if (node->isUserDefined())
1169 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001170 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1171 if (result) {
1172 builder.clearAccessChain();
1173 builder.setAccessChainRValue(result);
1174 } else
1175 spv::MissingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001176
1177 return false;
1178 }
1179 case glslang::EOpConstructMat2x2:
1180 case glslang::EOpConstructMat2x3:
1181 case glslang::EOpConstructMat2x4:
1182 case glslang::EOpConstructMat3x2:
1183 case glslang::EOpConstructMat3x3:
1184 case glslang::EOpConstructMat3x4:
1185 case glslang::EOpConstructMat4x2:
1186 case glslang::EOpConstructMat4x3:
1187 case glslang::EOpConstructMat4x4:
1188 case glslang::EOpConstructDMat2x2:
1189 case glslang::EOpConstructDMat2x3:
1190 case glslang::EOpConstructDMat2x4:
1191 case glslang::EOpConstructDMat3x2:
1192 case glslang::EOpConstructDMat3x3:
1193 case glslang::EOpConstructDMat3x4:
1194 case glslang::EOpConstructDMat4x2:
1195 case glslang::EOpConstructDMat4x3:
1196 case glslang::EOpConstructDMat4x4:
1197 isMatrix = true;
1198 // fall through
1199 case glslang::EOpConstructFloat:
1200 case glslang::EOpConstructVec2:
1201 case glslang::EOpConstructVec3:
1202 case glslang::EOpConstructVec4:
1203 case glslang::EOpConstructDouble:
1204 case glslang::EOpConstructDVec2:
1205 case glslang::EOpConstructDVec3:
1206 case glslang::EOpConstructDVec4:
1207 case glslang::EOpConstructBool:
1208 case glslang::EOpConstructBVec2:
1209 case glslang::EOpConstructBVec3:
1210 case glslang::EOpConstructBVec4:
1211 case glslang::EOpConstructInt:
1212 case glslang::EOpConstructIVec2:
1213 case glslang::EOpConstructIVec3:
1214 case glslang::EOpConstructIVec4:
1215 case glslang::EOpConstructUint:
1216 case glslang::EOpConstructUVec2:
1217 case glslang::EOpConstructUVec3:
1218 case glslang::EOpConstructUVec4:
1219 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001220 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001221 {
1222 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001223 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001224 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1225 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001226 if (node->getOp() == glslang::EOpConstructTextureSampler)
1227 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1228 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001229 std::vector<spv::Id> constituents;
1230 for (int c = 0; c < (int)arguments.size(); ++c)
1231 constituents.push_back(arguments[c]);
1232 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001233 } else if (isMatrix)
1234 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1235 else
1236 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001237
1238 builder.clearAccessChain();
1239 builder.setAccessChainRValue(constructed);
1240
1241 return false;
1242 }
1243
1244 // These six are component-wise compares with component-wise results.
1245 // Forward on to createBinaryOperation(), requesting a vector result.
1246 case glslang::EOpLessThan:
1247 case glslang::EOpGreaterThan:
1248 case glslang::EOpLessThanEqual:
1249 case glslang::EOpGreaterThanEqual:
1250 case glslang::EOpVectorEqual:
1251 case glslang::EOpVectorNotEqual:
1252 {
1253 // Map the operation to a binary
1254 binOp = node->getOp();
1255 reduceComparison = false;
1256 switch (node->getOp()) {
1257 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1258 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1259 default: binOp = node->getOp(); break;
1260 }
1261
1262 break;
1263 }
1264 case glslang::EOpMul:
1265 // compontent-wise matrix multiply
1266 binOp = glslang::EOpMul;
1267 break;
1268 case glslang::EOpOuterProduct:
1269 // two vectors multiplied to make a matrix
1270 binOp = glslang::EOpOuterProduct;
1271 break;
1272 case glslang::EOpDot:
1273 {
1274 // for scalar dot product, use multiply
1275 glslang::TIntermSequence& glslangOperands = node->getSequence();
1276 if (! glslangOperands[0]->getAsTyped()->isVector())
1277 binOp = glslang::EOpMul;
1278 break;
1279 }
1280 case glslang::EOpMod:
1281 // when an aggregate, this is the floating-point mod built-in function,
1282 // which can be emitted by the one in createBinaryOperation()
1283 binOp = glslang::EOpMod;
1284 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001285 case glslang::EOpEmitVertex:
1286 case glslang::EOpEndPrimitive:
1287 case glslang::EOpBarrier:
1288 case glslang::EOpMemoryBarrier:
1289 case glslang::EOpMemoryBarrierAtomicCounter:
1290 case glslang::EOpMemoryBarrierBuffer:
1291 case glslang::EOpMemoryBarrierImage:
1292 case glslang::EOpMemoryBarrierShared:
1293 case glslang::EOpGroupMemoryBarrier:
1294 noReturnValue = true;
1295 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1296 break;
1297
John Kessenich426394d2015-07-23 10:22:48 -06001298 case glslang::EOpAtomicAdd:
1299 case glslang::EOpAtomicMin:
1300 case glslang::EOpAtomicMax:
1301 case glslang::EOpAtomicAnd:
1302 case glslang::EOpAtomicOr:
1303 case glslang::EOpAtomicXor:
1304 case glslang::EOpAtomicExchange:
1305 case glslang::EOpAtomicCompSwap:
1306 atomic = true;
1307 break;
1308
John Kessenich140f3df2015-06-26 16:58:36 -06001309 default:
1310 break;
1311 }
1312
1313 //
1314 // See if it maps to a regular operation.
1315 //
John Kessenich140f3df2015-06-26 16:58:36 -06001316 if (binOp != glslang::EOpNull) {
1317 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1318 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1319 assert(left && right);
1320
1321 builder.clearAccessChain();
1322 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001323 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001324
1325 builder.clearAccessChain();
1326 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001327 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001328
1329 result = createBinaryOperation(binOp, precision,
1330 convertGlslangToSpvType(node->getType()), leftId, rightId,
1331 left->getType().getBasicType(), reduceComparison);
1332
1333 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001334 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001335 builder.clearAccessChain();
1336 builder.setAccessChainRValue(result);
1337
1338 return false;
1339 }
1340
John Kessenich426394d2015-07-23 10:22:48 -06001341 //
1342 // Create the list of operands.
1343 //
John Kessenich140f3df2015-06-26 16:58:36 -06001344 glslang::TIntermSequence& glslangOperands = node->getSequence();
1345 std::vector<spv::Id> operands;
1346 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1347 builder.clearAccessChain();
1348 glslangOperands[arg]->traverse(this);
1349
1350 // special case l-value operands; there are just a few
1351 bool lvalue = false;
1352 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001353 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001354 case glslang::EOpModf:
1355 if (arg == 1)
1356 lvalue = true;
1357 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001358 case glslang::EOpInterpolateAtSample:
1359 case glslang::EOpInterpolateAtOffset:
1360 if (arg == 0)
1361 lvalue = true;
1362 break;
Rex Xud4782c12015-09-06 16:30:11 +08001363 case glslang::EOpAtomicAdd:
1364 case glslang::EOpAtomicMin:
1365 case glslang::EOpAtomicMax:
1366 case glslang::EOpAtomicAnd:
1367 case glslang::EOpAtomicOr:
1368 case glslang::EOpAtomicXor:
1369 case glslang::EOpAtomicExchange:
1370 case glslang::EOpAtomicCompSwap:
1371 if (arg == 0)
1372 lvalue = true;
1373 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001374 case glslang::EOpAddCarry:
1375 case glslang::EOpSubBorrow:
1376 if (arg == 2)
1377 lvalue = true;
1378 break;
1379 case glslang::EOpUMulExtended:
1380 case glslang::EOpIMulExtended:
1381 if (arg >= 2)
1382 lvalue = true;
1383 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001384 default:
1385 break;
1386 }
1387 if (lvalue)
1388 operands.push_back(builder.accessChainGetLValue());
1389 else
John Kessenich32cfd492016-02-02 12:37:46 -07001390 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001391 }
John Kessenich426394d2015-07-23 10:22:48 -06001392
1393 if (atomic) {
1394 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001395 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001396 } else {
1397 // Pass through to generic operations.
1398 switch (glslangOperands.size()) {
1399 case 0:
1400 result = createNoArgOperation(node->getOp());
1401 break;
1402 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001403 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001404 break;
1405 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001406 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001407 break;
1408 }
John Kessenich140f3df2015-06-26 16:58:36 -06001409 }
1410
1411 if (noReturnValue)
1412 return false;
1413
1414 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001415 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001416 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001417 } else {
1418 builder.clearAccessChain();
1419 builder.setAccessChainRValue(result);
1420 return false;
1421 }
1422}
1423
1424bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1425{
1426 // This path handles both if-then-else and ?:
1427 // The if-then-else has a node type of void, while
1428 // ?: has a non-void node type
1429 spv::Id result = 0;
1430 if (node->getBasicType() != glslang::EbtVoid) {
1431 // don't handle this as just on-the-fly temporaries, because there will be two names
1432 // and better to leave SSA to later passes
1433 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1434 }
1435
1436 // emit the condition before doing anything with selection
1437 node->getCondition()->traverse(this);
1438
1439 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001440 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001441
1442 if (node->getTrueBlock()) {
1443 // emit the "then" statement
1444 node->getTrueBlock()->traverse(this);
1445 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001446 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001447 }
1448
1449 if (node->getFalseBlock()) {
1450 ifBuilder.makeBeginElse();
1451 // emit the "else" statement
1452 node->getFalseBlock()->traverse(this);
1453 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001454 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001455 }
1456
1457 ifBuilder.makeEndIf();
1458
1459 if (result) {
1460 // GLSL only has r-values as the result of a :?, but
1461 // if we have an l-value, that can be more efficient if it will
1462 // become the base of a complex r-value expression, because the
1463 // next layer copies r-values into memory to use the access-chain mechanism
1464 builder.clearAccessChain();
1465 builder.setAccessChainLValue(result);
1466 }
1467
1468 return false;
1469}
1470
1471bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1472{
1473 // emit and get the condition before doing anything with switch
1474 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001475 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001476
1477 // browse the children to sort out code segments
1478 int defaultSegment = -1;
1479 std::vector<TIntermNode*> codeSegments;
1480 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1481 std::vector<int> caseValues;
1482 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1483 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1484 TIntermNode* child = *c;
1485 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001486 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001487 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001488 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001489 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1490 } else
1491 codeSegments.push_back(child);
1492 }
1493
1494 // handle the case where the last code segment is missing, due to no code
1495 // statements between the last case and the end of the switch statement
1496 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1497 (int)codeSegments.size() == defaultSegment)
1498 codeSegments.push_back(nullptr);
1499
1500 // make the switch statement
1501 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001502 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001503
1504 // emit all the code in the segments
1505 breakForLoop.push(false);
1506 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1507 builder.nextSwitchSegment(segmentBlocks, s);
1508 if (codeSegments[s])
1509 codeSegments[s]->traverse(this);
1510 else
1511 builder.addSwitchBreak();
1512 }
1513 breakForLoop.pop();
1514
1515 builder.endSwitch(segmentBlocks);
1516
1517 return false;
1518}
1519
1520void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1521{
1522 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001523 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001524
1525 builder.clearAccessChain();
1526 builder.setAccessChainRValue(constant);
1527}
1528
1529bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1530{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001531 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001532 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001533 // Spec requires back edges to target header blocks, and every header block
1534 // must dominate its merge block. Make a header block first to ensure these
1535 // conditions are met. By definition, it will contain OpLoopMerge, followed
1536 // by a block-ending branch. But we don't want to put any other body/test
1537 // instructions in it, since the body/test may have arbitrary instructions,
1538 // including merges of its own.
1539 builder.setBuildPoint(&blocks.head);
1540 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001541 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001542 spv::Block& test = builder.makeNewBlock();
1543 builder.createBranch(&test);
1544
1545 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001546 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001547 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001548 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001549 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1550
1551 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001552 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001553 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001554 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001555 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001556 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001557
1558 builder.setBuildPoint(&blocks.continue_target);
1559 if (node->getTerminal())
1560 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001561 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001562 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001563 builder.createBranch(&blocks.body);
1564
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001565 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001566 builder.setBuildPoint(&blocks.body);
1567 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001568 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001569 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001570 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001571
1572 builder.setBuildPoint(&blocks.continue_target);
1573 if (node->getTerminal())
1574 node->getTerminal()->traverse(this);
1575 if (node->getTest()) {
1576 node->getTest()->traverse(this);
1577 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001578 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001579 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001580 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001581 // TODO: unless there was a break/return/discard instruction
1582 // somewhere in the body, this is an infinite loop, so we should
1583 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001584 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001585 }
John Kessenich140f3df2015-06-26 16:58:36 -06001586 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001587 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001588 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001589 return false;
1590}
1591
1592bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1593{
1594 if (node->getExpression())
1595 node->getExpression()->traverse(this);
1596
1597 switch (node->getFlowOp()) {
1598 case glslang::EOpKill:
1599 builder.makeDiscard();
1600 break;
1601 case glslang::EOpBreak:
1602 if (breakForLoop.top())
1603 builder.createLoopExit();
1604 else
1605 builder.addSwitchBreak();
1606 break;
1607 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001608 builder.createLoopContinue();
1609 break;
1610 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001611 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001612 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001613 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001614 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001615
1616 builder.clearAccessChain();
1617 break;
1618
1619 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001620 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001621 break;
1622 }
1623
1624 return false;
1625}
1626
1627spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1628{
1629 // First, steer off constants, which are not SPIR-V variables, but
1630 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001631 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001632 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001633 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001634 }
1635
1636 // Now, handle actual variables
1637 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1638 spv::Id spvType = convertGlslangToSpvType(node->getType());
1639
1640 const char* name = node->getName().c_str();
1641 if (glslang::IsAnonymous(name))
1642 name = "";
1643
1644 return builder.createVariable(storageClass, spvType, name);
1645}
1646
1647// Return type Id of the sampled type.
1648spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1649{
1650 switch (sampler.type) {
1651 case glslang::EbtFloat: return builder.makeFloatType(32);
1652 case glslang::EbtInt: return builder.makeIntType(32);
1653 case glslang::EbtUint: return builder.makeUintType(32);
1654 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001655 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001656 return builder.makeFloatType(32);
1657 }
1658}
1659
John Kessenich3ac051e2015-12-20 11:29:16 -07001660// Convert from a glslang type to an SPV type, by calling into a
1661// recursive version of this function. This establishes the inherited
1662// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001663spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1664{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001665 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001666}
1667
1668// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001669// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001670spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001671{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001672 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001673
1674 switch (type.getBasicType()) {
1675 case glslang::EbtVoid:
1676 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001677 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001678 break;
1679 case glslang::EbtFloat:
1680 spvType = builder.makeFloatType(32);
1681 break;
1682 case glslang::EbtDouble:
1683 spvType = builder.makeFloatType(64);
1684 break;
1685 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001686 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1687 // a 32-bit int where non-0 means true.
1688 if (explicitLayout != glslang::ElpNone)
1689 spvType = builder.makeUintType(32);
1690 else
1691 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001692 break;
1693 case glslang::EbtInt:
1694 spvType = builder.makeIntType(32);
1695 break;
1696 case glslang::EbtUint:
1697 spvType = builder.makeUintType(32);
1698 break;
John Kessenich426394d2015-07-23 10:22:48 -06001699 case glslang::EbtAtomicUint:
1700 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1701 spvType = builder.makeUintType(32);
1702 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001703 case glslang::EbtSampler:
1704 {
1705 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001706 if (sampler.sampler) {
1707 // pure sampler
1708 spvType = builder.makeSamplerType();
1709 } else {
1710 // an image is present, make its type
1711 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1712 sampler.image ? 2 : 1, TranslateImageFormat(type));
1713 if (sampler.combined) {
1714 // already has both image and sampler, make the combined type
1715 spvType = builder.makeSampledImageType(spvType);
1716 }
John Kessenich55e7d112015-11-15 21:33:39 -07001717 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001718 }
John Kessenich140f3df2015-06-26 16:58:36 -06001719 break;
1720 case glslang::EbtStruct:
1721 case glslang::EbtBlock:
1722 {
1723 // If we've seen this struct type, return it
1724 const glslang::TTypeList* glslangStruct = type.getStruct();
1725 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001726
1727 // Try to share structs for different layouts, but not yet for other
1728 // kinds of qualification (primarily not yet including interpolant qualification).
1729 if (! HasNonLayoutQualifiers(qualifier))
1730 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1731 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001732 break;
1733
1734 // else, we haven't seen it...
1735
1736 // Create a vector of struct types for SPIR-V to consume
1737 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1738 if (type.getBasicType() == glslang::EbtBlock)
1739 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001740 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001741 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1742 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1743 if (glslangType.hiddenMember()) {
1744 ++memberDelta;
1745 if (type.getBasicType() == glslang::EbtBlock)
1746 memberRemapper[glslangStruct][i] = -1;
1747 } else {
1748 if (type.getBasicType() == glslang::EbtBlock)
1749 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001750 // modify just this child's view of the qualifier
1751 glslang::TQualifier subQualifier = glslangType.getQualifier();
1752 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001753
1754 // manually inherit location; it's more complex
1755 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1756 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1757 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001758 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001759
1760 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001761 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001762 }
1763 }
1764
1765 // Make the SPIR-V type
1766 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001767 if (! HasNonLayoutQualifiers(qualifier))
1768 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001769
1770 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001771 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001772 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001773 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1774 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1775 int member = i;
1776 if (type.getBasicType() == glslang::EbtBlock)
1777 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001778
John Kesseniche0b6cad2015-12-24 10:30:13 -07001779 // modify just this child's view of the qualifier
1780 glslang::TQualifier subQualifier = glslangType.getQualifier();
1781 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001782
John Kessenich140f3df2015-06-26 16:58:36 -06001783 // using -1 above to indicate a hidden member
1784 if (member >= 0) {
1785 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001786 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001787 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001788 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1789 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001790
Rex Xu1da878f2016-02-21 20:59:01 +08001791 if (qualifier.storage == glslang::EvqBuffer) {
1792 std::vector<spv::Decoration> memory;
1793 TranslateMemoryDecoration(subQualifier, memory);
1794 for (unsigned int i = 0; i < memory.size(); ++i)
1795 addMemberDecoration(spvType, member, memory[i]);
1796 }
1797
John Kessenich09677482016-02-19 12:21:50 -07001798 // compute location decoration; tricky based on whether inheritance is at play
1799 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1800 // probably move to the linker stage of the front end proper, and just have the
1801 // answer sitting already distributed throughout the individual member locations.
1802 int location = -1; // will only decorate if present or inherited
1803 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1804 location = subQualifier.layoutLocation;
1805 else if (qualifier.hasLocation()) // inheritance
1806 location = qualifier.layoutLocation + locationOffset;
1807 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001808 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001809 if (location >= 0)
1810 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1811
1812 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001813 if (glslangType.getQualifier().hasComponent())
1814 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1815 if (glslangType.getQualifier().hasXfbOffset())
1816 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001817 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001818 // figure out what to do with offset, which is accumulating
1819 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001820 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001821 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001822 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001823 offset = nextOffset;
1824 }
John Kessenich140f3df2015-06-26 16:58:36 -06001825
John Kessenichf85e8062015-12-19 13:57:10 -07001826 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001827 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001828
John Kessenich140f3df2015-06-26 16:58:36 -06001829 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001830 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1831 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001832 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001833 }
1834 }
1835
1836 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001837 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001838 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001839 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001840 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001841 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001842 }
John Kessenich140f3df2015-06-26 16:58:36 -06001843 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001844 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001845 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001846 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001847 if (type.getQualifier().hasXfbBuffer())
1848 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1849 }
1850 }
1851 break;
1852 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001853 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001854 break;
1855 }
1856
1857 if (type.isMatrix())
1858 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1859 else {
1860 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1861 if (type.getVectorSize() > 1)
1862 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1863 }
1864
1865 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001866 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1867
John Kessenichc9a80832015-09-12 12:17:44 -06001868 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001869 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001870 // We need to decorate array strides for types needing explicit layout, except blocks.
1871 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001872 // Use a dummy glslang type for querying internal strides of
1873 // arrays of arrays, but using just a one-dimensional array.
1874 glslang::TType simpleArrayType(type, 0); // deference type of the array
1875 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1876 simpleArrayType.getArraySizes().dereference();
1877
1878 // Will compute the higher-order strides here, rather than making a whole
1879 // pile of types and doing repetitive recursion on their contents.
1880 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1881 }
John Kessenichf8842e52016-01-04 19:22:56 -07001882
1883 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001884 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001885 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001886 if (stride > 0)
1887 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001888 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001889 }
1890 } else {
1891 // single-dimensional array, and don't yet have stride
1892
John Kessenichf8842e52016-01-04 19:22:56 -07001893 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001894 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1895 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001896 }
John Kessenich31ed4832015-09-09 17:51:38 -06001897
John Kessenichc9a80832015-09-12 12:17:44 -06001898 // Do the outer dimension, which might not be known for a runtime-sized array
1899 if (type.isRuntimeSizedArray()) {
1900 spvType = builder.makeRuntimeArray(spvType);
1901 } else {
1902 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001903 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001904 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001905 if (stride > 0)
1906 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001907 }
1908
1909 return spvType;
1910}
1911
John Kessenich6c292d32016-02-15 20:58:50 -07001912// Turn the expression forming the array size into an id.
1913// This is not quite trivial, because of specialization constants.
1914// Sometimes, a raw constant is turned into an Id, and sometimes
1915// a specialization constant expression is.
1916spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1917{
1918 // First, see if this is sized with a node, meaning a specialization constant:
1919 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1920 if (specNode != nullptr) {
1921 builder.clearAccessChain();
1922 specNode->traverse(this);
1923 return accessChainLoad(specNode->getAsTyped()->getType());
1924 }
1925
1926 // Otherwise, need a compile-time (front end) size, get it:
1927 int size = arraySizes.getDimSize(dim);
1928 assert(size > 0);
1929 return builder.makeUintConstant(size);
1930}
1931
John Kessenich103bef92016-02-08 21:38:15 -07001932// Wrap the builder's accessChainLoad to:
1933// - localize handling of RelaxedPrecision
1934// - use the SPIR-V inferred type instead of another conversion of the glslang type
1935// (avoids unnecessary work and possible type punning for structures)
1936// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001937spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1938{
John Kessenich103bef92016-02-08 21:38:15 -07001939 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1940 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1941
1942 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08001943 if (type.getBasicType() == glslang::EbtBool) {
1944 if (builder.isScalarType(nominalTypeId)) {
1945 // Conversion for bool
1946 spv::Id boolType = builder.makeBoolType();
1947 if (nominalTypeId != boolType)
1948 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
1949 } else if (builder.isVectorType(nominalTypeId)) {
1950 // Conversion for bvec
1951 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1952 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1953 if (nominalTypeId != bvecType)
1954 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
1955 }
1956 }
John Kessenich103bef92016-02-08 21:38:15 -07001957
1958 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07001959}
1960
Rex Xu27253232016-02-23 17:51:09 +08001961// Wrap the builder's accessChainStore to:
1962// - do conversion of concrete to abstract type
1963void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
1964{
1965 // Need to convert to abstract types when necessary
1966 if (type.getBasicType() == glslang::EbtBool) {
1967 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1968
1969 if (builder.isScalarType(nominalTypeId)) {
1970 // Conversion for bool
1971 spv::Id boolType = builder.makeBoolType();
1972 if (nominalTypeId != boolType) {
1973 spv::Id zero = builder.makeUintConstant(0);
1974 spv::Id one = builder.makeUintConstant(1);
1975 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
1976 }
1977 } else if (builder.isVectorType(nominalTypeId)) {
1978 // Conversion for bvec
1979 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1980 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1981 if (nominalTypeId != bvecType) {
1982 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
1983 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
1984 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
1985 }
1986 }
1987 }
1988
1989 builder.accessChainStore(rvalue);
1990}
1991
John Kessenichf85e8062015-12-19 13:57:10 -07001992// Decide whether or not this type should be
1993// decorated with offsets and strides, and if so
1994// whether std140 or std430 rules should be applied.
1995glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001996{
John Kessenichf85e8062015-12-19 13:57:10 -07001997 // has to be a block
1998 if (type.getBasicType() != glslang::EbtBlock)
1999 return glslang::ElpNone;
2000
2001 // has to be a uniform or buffer block
2002 if (type.getQualifier().storage != glslang::EvqUniform &&
2003 type.getQualifier().storage != glslang::EvqBuffer)
2004 return glslang::ElpNone;
2005
2006 // return the layout to use
2007 switch (type.getQualifier().layoutPacking) {
2008 case glslang::ElpStd140:
2009 case glslang::ElpStd430:
2010 return type.getQualifier().layoutPacking;
2011 default:
2012 return glslang::ElpNone;
2013 }
John Kessenich31ed4832015-09-09 17:51:38 -06002014}
2015
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002016// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002017int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002018{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002019 int size;
John Kessenich49987892015-12-29 17:11:44 -07002020 int stride;
2021 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002022
2023 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002024}
2025
John Kessenich49987892015-12-29 17:11:44 -07002026// 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 -07002027// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002028int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002029{
John Kessenich49987892015-12-29 17:11:44 -07002030 glslang::TType elementType;
2031 elementType.shallowCopy(matrixType);
2032 elementType.clearArraySizes();
2033
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002034 int size;
John Kessenich49987892015-12-29 17:11:44 -07002035 int stride;
2036 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2037
2038 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002039}
2040
John Kessenich5e4b1242015-08-06 22:53:06 -06002041// Given a member type of a struct, realign the current offset for it, and compute
2042// the next (not yet aligned) offset for the next member, which will get aligned
2043// on the next call.
2044// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2045// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2046// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002047void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002048 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002049{
2050 // this will get a positive value when deemed necessary
2051 nextOffset = -1;
2052
John Kessenich5e4b1242015-08-06 22:53:06 -06002053 // override anything in currentOffset with user-set offset
2054 if (memberType.getQualifier().hasOffset())
2055 currentOffset = memberType.getQualifier().layoutOffset;
2056
2057 // It could be that current linker usage in glslang updated all the layoutOffset,
2058 // in which case the following code does not matter. But, that's not quite right
2059 // once cross-compilation unit GLSL validation is done, as the original user
2060 // settings are needed in layoutOffset, and then the following will come into play.
2061
John Kessenichf85e8062015-12-19 13:57:10 -07002062 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002063 if (! memberType.getQualifier().hasOffset())
2064 currentOffset = -1;
2065
2066 return;
2067 }
2068
John Kessenichf85e8062015-12-19 13:57:10 -07002069 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002070 if (currentOffset < 0)
2071 currentOffset = 0;
2072
2073 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2074 // but possibly not yet correctly aligned.
2075
2076 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002077 int dummyStride;
2078 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002079 glslang::RoundToPow2(currentOffset, memberAlignment);
2080 nextOffset = currentOffset + memberSize;
2081}
2082
John Kessenich140f3df2015-06-26 16:58:36 -06002083bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2084{
John Kessenich4d65ee32016-03-12 18:17:47 -07002085 // have to ignore mangling and just look at the base name
2086 int firstOpen = node->getName().find('(');
2087 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002088}
2089
2090// Make all the functions, skeletally, without actually visiting their bodies.
2091void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2092{
2093 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2094 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2095 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2096 continue;
2097
2098 // We're on a user function. Set up the basic interface for the function now,
2099 // so that it's available to call.
2100 // Translating the body will happen later.
2101 //
2102 // Typically (except for a "const in" parameter), an address will be passed to the
2103 // function. What it is an address of varies:
2104 //
2105 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2106 // so that write needs to be to a copy, hence the address of a copy works.
2107 //
2108 // - "const in" parameters can just be the r-value, as no writes need occur.
2109 //
2110 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2111 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2112
2113 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002114 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002115 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2116
2117 for (int p = 0; p < (int)parameters.size(); ++p) {
2118 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2119 spv::Id typeId = convertGlslangToSpvType(paramType);
2120 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2121 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2122 else
2123 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002124 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002125 paramTypes.push_back(typeId);
2126 }
2127
2128 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002129 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2130 convertGlslangToSpvType(glslFunction->getType()),
2131 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002132
2133 // Track function to emit/call later
2134 functionMap[glslFunction->getName().c_str()] = function;
2135
2136 // Set the parameter id's
2137 for (int p = 0; p < (int)parameters.size(); ++p) {
2138 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2139 // give a name too
2140 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2141 }
2142 }
2143}
2144
2145// Process all the initializers, while skipping the functions and link objects
2146void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2147{
2148 builder.setBuildPoint(shaderEntry->getLastBlock());
2149 for (int i = 0; i < (int)initializers.size(); ++i) {
2150 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2151 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2152
2153 // We're on a top-level node that's not a function. Treat as an initializer, whose
2154 // code goes into the beginning of main.
2155 initializer->traverse(this);
2156 }
2157 }
2158}
2159
2160// Process all the functions, while skipping initializers.
2161void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2162{
2163 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2164 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2165 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2166 node->traverse(this);
2167 }
2168}
2169
2170void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2171{
2172 // SPIR-V functions should already be in the functionMap from the prepass
2173 // that called makeFunctions().
2174 spv::Function* function = functionMap[node->getName().c_str()];
2175 spv::Block* functionBlock = function->getEntryBlock();
2176 builder.setBuildPoint(functionBlock);
2177}
2178
Rex Xu04db3f52015-09-16 11:44:02 +08002179void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002180{
Rex Xufc618912015-09-09 16:42:49 +08002181 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002182
2183 glslang::TSampler sampler = {};
2184 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002185 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002186 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2187 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2188 }
2189
John Kessenich140f3df2015-06-26 16:58:36 -06002190 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2191 builder.clearAccessChain();
2192 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002193
2194 // Special case l-value operands
2195 bool lvalue = false;
2196 switch (node.getOp()) {
2197 case glslang::EOpImageAtomicAdd:
2198 case glslang::EOpImageAtomicMin:
2199 case glslang::EOpImageAtomicMax:
2200 case glslang::EOpImageAtomicAnd:
2201 case glslang::EOpImageAtomicOr:
2202 case glslang::EOpImageAtomicXor:
2203 case glslang::EOpImageAtomicExchange:
2204 case glslang::EOpImageAtomicCompSwap:
2205 if (i == 0)
2206 lvalue = true;
2207 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002208 case glslang::EOpSparseImageLoad:
2209 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2210 lvalue = true;
2211 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002212 case glslang::EOpSparseTexture:
2213 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2214 lvalue = true;
2215 break;
2216 case glslang::EOpSparseTextureClamp:
2217 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2218 lvalue = true;
2219 break;
2220 case glslang::EOpSparseTextureLod:
2221 case glslang::EOpSparseTextureOffset:
2222 if (i == 3)
2223 lvalue = true;
2224 break;
2225 case glslang::EOpSparseTextureFetch:
2226 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2227 lvalue = true;
2228 break;
2229 case glslang::EOpSparseTextureFetchOffset:
2230 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2231 lvalue = true;
2232 break;
2233 case glslang::EOpSparseTextureLodOffset:
2234 case glslang::EOpSparseTextureGrad:
2235 case glslang::EOpSparseTextureOffsetClamp:
2236 if (i == 4)
2237 lvalue = true;
2238 break;
2239 case glslang::EOpSparseTextureGradOffset:
2240 case glslang::EOpSparseTextureGradClamp:
2241 if (i == 5)
2242 lvalue = true;
2243 break;
2244 case glslang::EOpSparseTextureGradOffsetClamp:
2245 if (i == 6)
2246 lvalue = true;
2247 break;
2248 case glslang::EOpSparseTextureGather:
2249 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2250 lvalue = true;
2251 break;
2252 case glslang::EOpSparseTextureGatherOffset:
2253 case glslang::EOpSparseTextureGatherOffsets:
2254 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2255 lvalue = true;
2256 break;
Rex Xufc618912015-09-09 16:42:49 +08002257 default:
2258 break;
2259 }
2260
Rex Xu6b86d492015-09-16 17:48:22 +08002261 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002262 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002263 else
John Kessenich32cfd492016-02-02 12:37:46 -07002264 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002265 }
2266}
2267
John Kessenichfc51d282015-08-19 13:34:18 -06002268void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002269{
John Kessenichfc51d282015-08-19 13:34:18 -06002270 builder.clearAccessChain();
2271 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002272 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002273}
John Kessenich140f3df2015-06-26 16:58:36 -06002274
John Kessenichfc51d282015-08-19 13:34:18 -06002275spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2276{
Rex Xufc618912015-09-09 16:42:49 +08002277 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002278 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002279 }
2280
John Kessenichfc51d282015-08-19 13:34:18 -06002281 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002282 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2283 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2284 std::vector<spv::Id> arguments;
2285 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002286 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002287 else
2288 translateArguments(*node->getAsUnaryNode(), arguments);
2289 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2290
2291 spv::Builder::TextureParameters params = { };
2292 params.sampler = arguments[0];
2293
Rex Xu04db3f52015-09-16 11:44:02 +08002294 glslang::TCrackedTextureOp cracked;
2295 node->crackTexture(sampler, cracked);
2296
John Kessenichfc51d282015-08-19 13:34:18 -06002297 // Check for queries
2298 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002299 // a sampled image needs to have the image extracted first
2300 if (builder.isSampledImage(params.sampler))
2301 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002302 switch (node->getOp()) {
2303 case glslang::EOpImageQuerySize:
2304 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002305 if (arguments.size() > 1) {
2306 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002307 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002308 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002309 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002310 case glslang::EOpImageQuerySamples:
2311 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002312 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002313 case glslang::EOpTextureQueryLod:
2314 params.coords = arguments[1];
2315 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2316 case glslang::EOpTextureQueryLevels:
2317 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002318 case glslang::EOpSparseTexelsResident:
2319 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002320 default:
2321 assert(0);
2322 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002323 }
John Kessenich140f3df2015-06-26 16:58:36 -06002324 }
2325
Rex Xufc618912015-09-09 16:42:49 +08002326 // Check for image functions other than queries
2327 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002328 std::vector<spv::Id> operands;
2329 auto opIt = arguments.begin();
2330 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002331
2332 // Handle subpass operations
2333 // TODO: GLSL should change to have the "MS" only on the type rather than the
2334 // built-in function.
2335 if (cracked.subpass) {
2336 // add on the (0,0) coordinate
2337 spv::Id zero = builder.makeIntConstant(0);
2338 std::vector<spv::Id> comps;
2339 comps.push_back(zero);
2340 comps.push_back(zero);
2341 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2342 if (sampler.ms) {
2343 operands.push_back(spv::ImageOperandsSampleMask);
2344 operands.push_back(*(opIt++));
2345 }
2346 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2347 }
2348
John Kessenich56bab042015-09-16 10:54:31 -06002349 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002350 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002351 if (sampler.ms) {
2352 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002353 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002354 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002355 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2356 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002357 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002358 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002359 if (sampler.ms) {
2360 operands.push_back(*(opIt + 1));
2361 operands.push_back(spv::ImageOperandsSampleMask);
2362 operands.push_back(*opIt);
2363 } else
2364 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002365 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002366 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2367 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002368 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002369 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2370 builder.addCapability(spv::CapabilitySparseResidency);
2371 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2372 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2373
2374 if (sampler.ms) {
2375 operands.push_back(spv::ImageOperandsSampleMask);
2376 operands.push_back(*opIt++);
2377 }
2378
2379 // Create the return type that was a special structure
2380 spv::Id texelOut = *opIt;
2381 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2382 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2383 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2384
2385 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2386
2387 // Decode the return type
2388 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2389 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002390 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002391 // Process image atomic operations
2392
2393 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2394 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002395 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002396
Rex Xufc618912015-09-09 16:42:49 +08002397 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002398 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002399
2400 std::vector<spv::Id> operands;
2401 operands.push_back(pointer);
2402 for (; opIt != arguments.end(); ++opIt)
2403 operands.push_back(*opIt);
2404
Rex Xu04db3f52015-09-16 11:44:02 +08002405 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002406 }
2407 }
2408
2409 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002410 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002411 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2412
John Kessenichfc51d282015-08-19 13:34:18 -06002413 // check for bias argument
2414 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002415 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002416 int nonBiasArgCount = 2;
2417 if (cracked.offset)
2418 ++nonBiasArgCount;
2419 if (cracked.grad)
2420 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002421 if (cracked.lodClamp)
2422 ++nonBiasArgCount;
2423 if (sparse)
2424 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002425
2426 if ((int)arguments.size() > nonBiasArgCount)
2427 bias = true;
2428 }
2429
John Kessenichfc51d282015-08-19 13:34:18 -06002430 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002431
John Kessenichfc51d282015-08-19 13:34:18 -06002432 params.coords = arguments[1];
2433 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002434 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002435
2436 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002437 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002438 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002439 ++extraArgs;
2440 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002441 params.Dref = arguments[2];
2442 ++extraArgs;
2443 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002444 std::vector<spv::Id> indexes;
2445 int comp;
2446 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002447 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002448 else
2449 comp = builder.getNumComponents(params.coords) - 1;
2450 indexes.push_back(comp);
2451 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2452 }
2453 if (cracked.lod) {
2454 params.lod = arguments[2];
2455 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002456 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2457 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2458 noImplicitLod = true;
2459 }
2460 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002461 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002462 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002463 }
2464 if (cracked.grad) {
2465 params.gradX = arguments[2 + extraArgs];
2466 params.gradY = arguments[3 + extraArgs];
2467 extraArgs += 2;
2468 }
John Kessenich55e7d112015-11-15 21:33:39 -07002469 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002470 params.offset = arguments[2 + extraArgs];
2471 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002472 } else if (cracked.offsets) {
2473 params.offsets = arguments[2 + extraArgs];
2474 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002475 }
Rex Xu48edadf2015-12-31 16:11:41 +08002476 if (cracked.lodClamp) {
2477 params.lodClamp = arguments[2 + extraArgs];
2478 ++extraArgs;
2479 }
2480 if (sparse) {
2481 params.texelOut = arguments[2 + extraArgs];
2482 ++extraArgs;
2483 }
John Kessenichfc51d282015-08-19 13:34:18 -06002484 if (bias) {
2485 params.bias = arguments[2 + extraArgs];
2486 ++extraArgs;
2487 }
John Kessenich55e7d112015-11-15 21:33:39 -07002488 if (cracked.gather && ! sampler.shadow) {
2489 // default component is 0, if missing, otherwise an argument
2490 if (2 + extraArgs < (int)arguments.size()) {
2491 params.comp = arguments[2 + extraArgs];
2492 ++extraArgs;
2493 } else {
2494 params.comp = builder.makeIntConstant(0);
2495 }
2496 }
John Kessenichfc51d282015-08-19 13:34:18 -06002497
John Kessenich019f08f2016-02-15 15:40:42 -07002498 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002499}
2500
2501spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2502{
2503 // Grab the function's pointer from the previously created function
2504 spv::Function* function = functionMap[node->getName().c_str()];
2505 if (! function)
2506 return 0;
2507
2508 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2509 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2510
2511 // See comments in makeFunctions() for details about the semantics for parameter passing.
2512 //
2513 // These imply we need a four step process:
2514 // 1. Evaluate the arguments
2515 // 2. Allocate and make copies of in, out, and inout arguments
2516 // 3. Make the call
2517 // 4. Copy back the results
2518
2519 // 1. Evaluate the arguments
2520 std::vector<spv::Builder::AccessChain> lValues;
2521 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002522 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002523 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2524 // build l-value
2525 builder.clearAccessChain();
2526 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002527 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002528 // keep outputs as l-values, evaluate input-only as r-values
2529 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2530 // save l-value
2531 lValues.push_back(builder.getAccessChain());
2532 } else {
2533 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002534 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002535 }
2536 }
2537
2538 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2539 // copy the original into that space.
2540 //
2541 // Also, build up the list of actual arguments to pass in for the call
2542 int lValueCount = 0;
2543 int rValueCount = 0;
2544 std::vector<spv::Id> spvArgs;
2545 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2546 spv::Id arg;
2547 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2548 // need space to hold the copy
2549 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2550 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2551 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2552 // need to copy the input into output space
2553 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002554 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002555 builder.createStore(copy, arg);
2556 }
2557 ++lValueCount;
2558 } else {
2559 arg = rValues[rValueCount];
2560 ++rValueCount;
2561 }
2562 spvArgs.push_back(arg);
2563 }
2564
2565 // 3. Make the call.
2566 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002567 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002568
2569 // 4. Copy back out an "out" arguments.
2570 lValueCount = 0;
2571 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2572 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2573 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2574 spv::Id copy = builder.createLoad(spvArgs[a]);
2575 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002576 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002577 }
2578 ++lValueCount;
2579 }
2580 }
2581
2582 return result;
2583}
2584
2585// Translate AST operation to SPV operation, already having SPV-based operands/types.
2586spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2587 spv::Id typeId, spv::Id left, spv::Id right,
2588 glslang::TBasicType typeProxy, bool reduceComparison)
2589{
2590 bool isUnsigned = typeProxy == glslang::EbtUint;
2591 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2592
2593 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002594 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002595 bool comparison = false;
2596
2597 switch (op) {
2598 case glslang::EOpAdd:
2599 case glslang::EOpAddAssign:
2600 if (isFloat)
2601 binOp = spv::OpFAdd;
2602 else
2603 binOp = spv::OpIAdd;
2604 break;
2605 case glslang::EOpSub:
2606 case glslang::EOpSubAssign:
2607 if (isFloat)
2608 binOp = spv::OpFSub;
2609 else
2610 binOp = spv::OpISub;
2611 break;
2612 case glslang::EOpMul:
2613 case glslang::EOpMulAssign:
2614 if (isFloat)
2615 binOp = spv::OpFMul;
2616 else
2617 binOp = spv::OpIMul;
2618 break;
2619 case glslang::EOpVectorTimesScalar:
2620 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002621 if (isFloat) {
2622 if (builder.isVector(right))
2623 std::swap(left, right);
2624 assert(builder.isScalar(right));
2625 needMatchingVectors = false;
2626 binOp = spv::OpVectorTimesScalar;
2627 } else
2628 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002629 break;
2630 case glslang::EOpVectorTimesMatrix:
2631 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002632 binOp = spv::OpVectorTimesMatrix;
2633 break;
2634 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002635 binOp = spv::OpMatrixTimesVector;
2636 break;
2637 case glslang::EOpMatrixTimesScalar:
2638 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002639 binOp = spv::OpMatrixTimesScalar;
2640 break;
2641 case glslang::EOpMatrixTimesMatrix:
2642 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002643 binOp = spv::OpMatrixTimesMatrix;
2644 break;
2645 case glslang::EOpOuterProduct:
2646 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002647 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002648 break;
2649
2650 case glslang::EOpDiv:
2651 case glslang::EOpDivAssign:
2652 if (isFloat)
2653 binOp = spv::OpFDiv;
2654 else if (isUnsigned)
2655 binOp = spv::OpUDiv;
2656 else
2657 binOp = spv::OpSDiv;
2658 break;
2659 case glslang::EOpMod:
2660 case glslang::EOpModAssign:
2661 if (isFloat)
2662 binOp = spv::OpFMod;
2663 else if (isUnsigned)
2664 binOp = spv::OpUMod;
2665 else
2666 binOp = spv::OpSMod;
2667 break;
2668 case glslang::EOpRightShift:
2669 case glslang::EOpRightShiftAssign:
2670 if (isUnsigned)
2671 binOp = spv::OpShiftRightLogical;
2672 else
2673 binOp = spv::OpShiftRightArithmetic;
2674 break;
2675 case glslang::EOpLeftShift:
2676 case glslang::EOpLeftShiftAssign:
2677 binOp = spv::OpShiftLeftLogical;
2678 break;
2679 case glslang::EOpAnd:
2680 case glslang::EOpAndAssign:
2681 binOp = spv::OpBitwiseAnd;
2682 break;
2683 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002684 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002685 binOp = spv::OpLogicalAnd;
2686 break;
2687 case glslang::EOpInclusiveOr:
2688 case glslang::EOpInclusiveOrAssign:
2689 binOp = spv::OpBitwiseOr;
2690 break;
2691 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002692 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002693 binOp = spv::OpLogicalOr;
2694 break;
2695 case glslang::EOpExclusiveOr:
2696 case glslang::EOpExclusiveOrAssign:
2697 binOp = spv::OpBitwiseXor;
2698 break;
2699 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002700 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002701 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002702 break;
2703
2704 case glslang::EOpLessThan:
2705 case glslang::EOpGreaterThan:
2706 case glslang::EOpLessThanEqual:
2707 case glslang::EOpGreaterThanEqual:
2708 case glslang::EOpEqual:
2709 case glslang::EOpNotEqual:
2710 case glslang::EOpVectorEqual:
2711 case glslang::EOpVectorNotEqual:
2712 comparison = true;
2713 break;
2714 default:
2715 break;
2716 }
2717
John Kessenich7c1aa102015-10-15 13:29:11 -06002718 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002719 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002720 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002721 if (builder.isMatrix(left) || builder.isMatrix(right))
2722 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002723
2724 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002725 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002726 builder.promoteScalar(precision, left, right);
2727
John Kessenich32cfd492016-02-02 12:37:46 -07002728 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002729 }
2730
2731 if (! comparison)
2732 return 0;
2733
John Kessenich7c1aa102015-10-15 13:29:11 -06002734 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002735
2736 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2737 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2738
John Kessenich22118352015-12-21 20:54:09 -07002739 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002740 }
2741
2742 switch (op) {
2743 case glslang::EOpLessThan:
2744 if (isFloat)
2745 binOp = spv::OpFOrdLessThan;
2746 else if (isUnsigned)
2747 binOp = spv::OpULessThan;
2748 else
2749 binOp = spv::OpSLessThan;
2750 break;
2751 case glslang::EOpGreaterThan:
2752 if (isFloat)
2753 binOp = spv::OpFOrdGreaterThan;
2754 else if (isUnsigned)
2755 binOp = spv::OpUGreaterThan;
2756 else
2757 binOp = spv::OpSGreaterThan;
2758 break;
2759 case glslang::EOpLessThanEqual:
2760 if (isFloat)
2761 binOp = spv::OpFOrdLessThanEqual;
2762 else if (isUnsigned)
2763 binOp = spv::OpULessThanEqual;
2764 else
2765 binOp = spv::OpSLessThanEqual;
2766 break;
2767 case glslang::EOpGreaterThanEqual:
2768 if (isFloat)
2769 binOp = spv::OpFOrdGreaterThanEqual;
2770 else if (isUnsigned)
2771 binOp = spv::OpUGreaterThanEqual;
2772 else
2773 binOp = spv::OpSGreaterThanEqual;
2774 break;
2775 case glslang::EOpEqual:
2776 case glslang::EOpVectorEqual:
2777 if (isFloat)
2778 binOp = spv::OpFOrdEqual;
2779 else
2780 binOp = spv::OpIEqual;
2781 break;
2782 case glslang::EOpNotEqual:
2783 case glslang::EOpVectorNotEqual:
2784 if (isFloat)
2785 binOp = spv::OpFOrdNotEqual;
2786 else
2787 binOp = spv::OpINotEqual;
2788 break;
2789 default:
2790 break;
2791 }
2792
John Kessenich32cfd492016-02-02 12:37:46 -07002793 if (binOp != spv::OpNop)
2794 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002795
2796 return 0;
2797}
2798
John Kessenich04bb8a02015-12-12 12:28:14 -07002799//
2800// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2801// These can be any of:
2802//
2803// matrix * scalar
2804// scalar * matrix
2805// matrix * matrix linear algebraic
2806// matrix * vector
2807// vector * matrix
2808// matrix * matrix componentwise
2809// matrix op matrix op in {+, -, /}
2810// matrix op scalar op in {+, -, /}
2811// scalar op matrix op in {+, -, /}
2812//
2813spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2814{
2815 bool firstClass = true;
2816
2817 // First, handle first-class matrix operations (* and matrix/scalar)
2818 switch (op) {
2819 case spv::OpFDiv:
2820 if (builder.isMatrix(left) && builder.isScalar(right)) {
2821 // turn matrix / scalar into a multiply...
2822 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2823 op = spv::OpMatrixTimesScalar;
2824 } else
2825 firstClass = false;
2826 break;
2827 case spv::OpMatrixTimesScalar:
2828 if (builder.isMatrix(right))
2829 std::swap(left, right);
2830 assert(builder.isScalar(right));
2831 break;
2832 case spv::OpVectorTimesMatrix:
2833 assert(builder.isVector(left));
2834 assert(builder.isMatrix(right));
2835 break;
2836 case spv::OpMatrixTimesVector:
2837 assert(builder.isMatrix(left));
2838 assert(builder.isVector(right));
2839 break;
2840 case spv::OpMatrixTimesMatrix:
2841 assert(builder.isMatrix(left));
2842 assert(builder.isMatrix(right));
2843 break;
2844 default:
2845 firstClass = false;
2846 break;
2847 }
2848
John Kessenich32cfd492016-02-02 12:37:46 -07002849 if (firstClass)
2850 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002851
2852 // Handle component-wise +, -, *, and / for all combinations of type.
2853 // The result type of all of them is the same type as the (a) matrix operand.
2854 // The algorithm is to:
2855 // - break the matrix(es) into vectors
2856 // - smear any scalar to a vector
2857 // - do vector operations
2858 // - make a matrix out the vector results
2859 switch (op) {
2860 case spv::OpFAdd:
2861 case spv::OpFSub:
2862 case spv::OpFDiv:
2863 case spv::OpFMul:
2864 {
2865 // one time set up...
2866 bool leftMat = builder.isMatrix(left);
2867 bool rightMat = builder.isMatrix(right);
2868 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2869 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2870 spv::Id scalarType = builder.getScalarTypeId(typeId);
2871 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2872 std::vector<spv::Id> results;
2873 spv::Id smearVec = spv::NoResult;
2874 if (builder.isScalar(left))
2875 smearVec = builder.smearScalar(precision, left, vecType);
2876 else if (builder.isScalar(right))
2877 smearVec = builder.smearScalar(precision, right, vecType);
2878
2879 // do each vector op
2880 for (unsigned int c = 0; c < numCols; ++c) {
2881 std::vector<unsigned int> indexes;
2882 indexes.push_back(c);
2883 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2884 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2885 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2886 builder.setPrecision(results.back(), precision);
2887 }
2888
2889 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002890 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002891 }
2892 default:
2893 assert(0);
2894 return spv::NoResult;
2895 }
2896}
2897
Rex Xu04db3f52015-09-16 11:44:02 +08002898spv::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 -06002899{
2900 spv::Op unaryOp = spv::OpNop;
2901 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002902 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002903 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002904
2905 switch (op) {
2906 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002907 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002908 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002909 if (builder.isMatrixType(typeId))
2910 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2911 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002912 unaryOp = spv::OpSNegate;
2913 break;
2914
2915 case glslang::EOpLogicalNot:
2916 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002917 unaryOp = spv::OpLogicalNot;
2918 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002919 case glslang::EOpBitwiseNot:
2920 unaryOp = spv::OpNot;
2921 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002922
John Kessenich140f3df2015-06-26 16:58:36 -06002923 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002924 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002925 break;
2926 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002927 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002928 break;
2929 case glslang::EOpTranspose:
2930 unaryOp = spv::OpTranspose;
2931 break;
2932
2933 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002934 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002935 break;
2936 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002937 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002938 break;
2939 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002940 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002941 break;
2942 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002943 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002944 break;
2945 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002946 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002947 break;
2948 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002949 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002950 break;
2951 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002952 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002953 break;
2954 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002955 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002956 break;
2957
2958 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002959 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002960 break;
2961 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002962 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002963 break;
2964 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002965 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002966 break;
2967 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002968 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002969 break;
2970 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002971 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002972 break;
2973 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002974 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002975 break;
2976
2977 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002978 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002979 break;
2980 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002981 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002982 break;
2983
2984 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002985 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002986 break;
2987 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002988 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002989 break;
2990 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002991 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002992 break;
2993 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002994 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002995 break;
2996 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002997 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002998 break;
2999 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003000 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003001 break;
3002
3003 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003004 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003005 break;
3006 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003007 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003008 break;
3009 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003010 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003011 break;
3012 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003013 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003014 break;
3015 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003016 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003017 break;
3018 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003019 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003020 break;
3021
3022 case glslang::EOpIsNan:
3023 unaryOp = spv::OpIsNan;
3024 break;
3025 case glslang::EOpIsInf:
3026 unaryOp = spv::OpIsInf;
3027 break;
3028
Rex Xucbc426e2015-12-15 16:03:10 +08003029 case glslang::EOpFloatBitsToInt:
3030 case glslang::EOpFloatBitsToUint:
3031 case glslang::EOpIntBitsToFloat:
3032 case glslang::EOpUintBitsToFloat:
3033 unaryOp = spv::OpBitcast;
3034 break;
3035
John Kessenich140f3df2015-06-26 16:58:36 -06003036 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003037 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003038 break;
3039 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003040 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003041 break;
3042 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003043 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003044 break;
3045 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003046 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003047 break;
3048 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003049 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003050 break;
3051 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003052 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003053 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003054 case glslang::EOpPackSnorm4x8:
3055 libCall = spv::GLSLstd450PackSnorm4x8;
3056 break;
3057 case glslang::EOpUnpackSnorm4x8:
3058 libCall = spv::GLSLstd450UnpackSnorm4x8;
3059 break;
3060 case glslang::EOpPackUnorm4x8:
3061 libCall = spv::GLSLstd450PackUnorm4x8;
3062 break;
3063 case glslang::EOpUnpackUnorm4x8:
3064 libCall = spv::GLSLstd450UnpackUnorm4x8;
3065 break;
3066 case glslang::EOpPackDouble2x32:
3067 libCall = spv::GLSLstd450PackDouble2x32;
3068 break;
3069 case glslang::EOpUnpackDouble2x32:
3070 libCall = spv::GLSLstd450UnpackDouble2x32;
3071 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003072
3073 case glslang::EOpDPdx:
3074 unaryOp = spv::OpDPdx;
3075 break;
3076 case glslang::EOpDPdy:
3077 unaryOp = spv::OpDPdy;
3078 break;
3079 case glslang::EOpFwidth:
3080 unaryOp = spv::OpFwidth;
3081 break;
3082 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003083 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003084 unaryOp = spv::OpDPdxFine;
3085 break;
3086 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003087 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003088 unaryOp = spv::OpDPdyFine;
3089 break;
3090 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003091 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003092 unaryOp = spv::OpFwidthFine;
3093 break;
3094 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003095 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003096 unaryOp = spv::OpDPdxCoarse;
3097 break;
3098 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003099 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003100 unaryOp = spv::OpDPdyCoarse;
3101 break;
3102 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003103 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003104 unaryOp = spv::OpFwidthCoarse;
3105 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003106 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003107 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003108 libCall = spv::GLSLstd450InterpolateAtCentroid;
3109 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003110 case glslang::EOpAny:
3111 unaryOp = spv::OpAny;
3112 break;
3113 case glslang::EOpAll:
3114 unaryOp = spv::OpAll;
3115 break;
3116
3117 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003118 if (isFloat)
3119 libCall = spv::GLSLstd450FAbs;
3120 else
3121 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003122 break;
3123 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003124 if (isFloat)
3125 libCall = spv::GLSLstd450FSign;
3126 else
3127 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003128 break;
3129
John Kessenichfc51d282015-08-19 13:34:18 -06003130 case glslang::EOpAtomicCounterIncrement:
3131 case glslang::EOpAtomicCounterDecrement:
3132 case glslang::EOpAtomicCounter:
3133 {
3134 // Handle all of the atomics in one place, in createAtomicOperation()
3135 std::vector<spv::Id> operands;
3136 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003137 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003138 }
3139
John Kessenichfc51d282015-08-19 13:34:18 -06003140 case glslang::EOpBitFieldReverse:
3141 unaryOp = spv::OpBitReverse;
3142 break;
3143 case glslang::EOpBitCount:
3144 unaryOp = spv::OpBitCount;
3145 break;
3146 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003147 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003148 break;
3149 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003150 if (isUnsigned)
3151 libCall = spv::GLSLstd450FindUMsb;
3152 else
3153 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003154 break;
3155
John Kessenich140f3df2015-06-26 16:58:36 -06003156 default:
3157 return 0;
3158 }
3159
3160 spv::Id id;
3161 if (libCall >= 0) {
3162 std::vector<spv::Id> args;
3163 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003164 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003165 } else
3166 id = builder.createUnaryOp(unaryOp, typeId, operand);
3167
John Kessenich32cfd492016-02-02 12:37:46 -07003168 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003169}
3170
John Kessenich7a53f762016-01-20 11:19:27 -07003171// Create a unary operation on a matrix
3172spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3173{
3174 // Handle unary operations vector by vector.
3175 // The result type is the same type as the original type.
3176 // The algorithm is to:
3177 // - break the matrix into vectors
3178 // - apply the operation to each vector
3179 // - make a matrix out the vector results
3180
3181 // get the types sorted out
3182 int numCols = builder.getNumColumns(operand);
3183 int numRows = builder.getNumRows(operand);
3184 spv::Id scalarType = builder.getScalarTypeId(typeId);
3185 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3186 std::vector<spv::Id> results;
3187
3188 // do each vector op
3189 for (int c = 0; c < numCols; ++c) {
3190 std::vector<unsigned int> indexes;
3191 indexes.push_back(c);
3192 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3193 results.push_back(builder.createUnaryOp(op, vecType, vec));
3194 builder.setPrecision(results.back(), precision);
3195 }
3196
3197 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003198 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003199}
3200
John Kessenich140f3df2015-06-26 16:58:36 -06003201spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3202{
3203 spv::Op convOp = spv::OpNop;
3204 spv::Id zero = 0;
3205 spv::Id one = 0;
3206
3207 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3208
3209 switch (op) {
3210 case glslang::EOpConvIntToBool:
3211 case glslang::EOpConvUintToBool:
3212 zero = builder.makeUintConstant(0);
3213 zero = makeSmearedConstant(zero, vectorSize);
3214 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3215
3216 case glslang::EOpConvFloatToBool:
3217 zero = builder.makeFloatConstant(0.0F);
3218 zero = makeSmearedConstant(zero, vectorSize);
3219 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3220
3221 case glslang::EOpConvDoubleToBool:
3222 zero = builder.makeDoubleConstant(0.0);
3223 zero = makeSmearedConstant(zero, vectorSize);
3224 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3225
3226 case glslang::EOpConvBoolToFloat:
3227 convOp = spv::OpSelect;
3228 zero = builder.makeFloatConstant(0.0);
3229 one = builder.makeFloatConstant(1.0);
3230 break;
3231 case glslang::EOpConvBoolToDouble:
3232 convOp = spv::OpSelect;
3233 zero = builder.makeDoubleConstant(0.0);
3234 one = builder.makeDoubleConstant(1.0);
3235 break;
3236 case glslang::EOpConvBoolToInt:
3237 zero = builder.makeIntConstant(0);
3238 one = builder.makeIntConstant(1);
3239 convOp = spv::OpSelect;
3240 break;
3241 case glslang::EOpConvBoolToUint:
3242 zero = builder.makeUintConstant(0);
3243 one = builder.makeUintConstant(1);
3244 convOp = spv::OpSelect;
3245 break;
3246
3247 case glslang::EOpConvIntToFloat:
3248 case glslang::EOpConvIntToDouble:
3249 convOp = spv::OpConvertSToF;
3250 break;
3251
3252 case glslang::EOpConvUintToFloat:
3253 case glslang::EOpConvUintToDouble:
3254 convOp = spv::OpConvertUToF;
3255 break;
3256
3257 case glslang::EOpConvDoubleToFloat:
3258 case glslang::EOpConvFloatToDouble:
3259 convOp = spv::OpFConvert;
3260 break;
3261
3262 case glslang::EOpConvFloatToInt:
3263 case glslang::EOpConvDoubleToInt:
3264 convOp = spv::OpConvertFToS;
3265 break;
3266
3267 case glslang::EOpConvUintToInt:
3268 case glslang::EOpConvIntToUint:
3269 convOp = spv::OpBitcast;
3270 break;
3271
3272 case glslang::EOpConvFloatToUint:
3273 case glslang::EOpConvDoubleToUint:
3274 convOp = spv::OpConvertFToU;
3275 break;
3276 default:
3277 break;
3278 }
3279
3280 spv::Id result = 0;
3281 if (convOp == spv::OpNop)
3282 return result;
3283
3284 if (convOp == spv::OpSelect) {
3285 zero = makeSmearedConstant(zero, vectorSize);
3286 one = makeSmearedConstant(one, vectorSize);
3287 result = builder.createTriOp(convOp, destType, operand, one, zero);
3288 } else
3289 result = builder.createUnaryOp(convOp, destType, operand);
3290
John Kessenich32cfd492016-02-02 12:37:46 -07003291 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003292}
3293
3294spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3295{
3296 if (vectorSize == 0)
3297 return constant;
3298
3299 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3300 std::vector<spv::Id> components;
3301 for (int c = 0; c < vectorSize; ++c)
3302 components.push_back(constant);
3303 return builder.makeCompositeConstant(vectorTypeId, components);
3304}
3305
John Kessenich426394d2015-07-23 10:22:48 -06003306// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003307spv::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 -06003308{
3309 spv::Op opCode = spv::OpNop;
3310
3311 switch (op) {
3312 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003313 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003314 opCode = spv::OpAtomicIAdd;
3315 break;
3316 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003317 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003318 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003319 break;
3320 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003321 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003322 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003323 break;
3324 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003325 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003326 opCode = spv::OpAtomicAnd;
3327 break;
3328 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003329 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003330 opCode = spv::OpAtomicOr;
3331 break;
3332 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003333 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003334 opCode = spv::OpAtomicXor;
3335 break;
3336 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003337 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003338 opCode = spv::OpAtomicExchange;
3339 break;
3340 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003341 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003342 opCode = spv::OpAtomicCompareExchange;
3343 break;
3344 case glslang::EOpAtomicCounterIncrement:
3345 opCode = spv::OpAtomicIIncrement;
3346 break;
3347 case glslang::EOpAtomicCounterDecrement:
3348 opCode = spv::OpAtomicIDecrement;
3349 break;
3350 case glslang::EOpAtomicCounter:
3351 opCode = spv::OpAtomicLoad;
3352 break;
3353 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003354 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003355 break;
3356 }
3357
3358 // Sort out the operands
3359 // - mapping from glslang -> SPV
3360 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003361 // - compare-exchange swaps the value and comparator
3362 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003363 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3364 auto opIt = operands.begin(); // walk the glslang operands
3365 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003366 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3367 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3368 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003369 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3370 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003371 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003372 spvAtomicOperands.push_back(*(opIt + 1));
3373 spvAtomicOperands.push_back(*opIt);
3374 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003375 }
John Kessenich426394d2015-07-23 10:22:48 -06003376
John Kessenich3e60a6f2015-09-14 22:45:16 -06003377 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003378 for (; opIt != operands.end(); ++opIt)
3379 spvAtomicOperands.push_back(*opIt);
3380
3381 return builder.createOp(opCode, typeId, spvAtomicOperands);
3382}
3383
John Kessenich5e4b1242015-08-06 22:53:06 -06003384spv::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 -06003385{
John Kessenich5e4b1242015-08-06 22:53:06 -06003386 bool isUnsigned = typeProxy == glslang::EbtUint;
3387 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3388
John Kessenich140f3df2015-06-26 16:58:36 -06003389 spv::Op opCode = spv::OpNop;
3390 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003391 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003392 spv::Id typeId0 = 0;
3393 if (consumedOperands > 0)
3394 typeId0 = builder.getTypeId(operands[0]);
3395 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003396
3397 switch (op) {
3398 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003399 if (isFloat)
3400 libCall = spv::GLSLstd450FMin;
3401 else if (isUnsigned)
3402 libCall = spv::GLSLstd450UMin;
3403 else
3404 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003405 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003406 break;
3407 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003408 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003409 break;
3410 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003411 if (isFloat)
3412 libCall = spv::GLSLstd450FMax;
3413 else if (isUnsigned)
3414 libCall = spv::GLSLstd450UMax;
3415 else
3416 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003417 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003418 break;
3419 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003420 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003421 break;
3422 case glslang::EOpDot:
3423 opCode = spv::OpDot;
3424 break;
3425 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003426 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003427 break;
3428
3429 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003430 if (isFloat)
3431 libCall = spv::GLSLstd450FClamp;
3432 else if (isUnsigned)
3433 libCall = spv::GLSLstd450UClamp;
3434 else
3435 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003436 builder.promoteScalar(precision, operands.front(), operands[1]);
3437 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003438 break;
3439 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003440 if (isFloat)
3441 libCall = spv::GLSLstd450FMix;
John Kessenich6c292d32016-02-15 20:58:50 -07003442 else {
3443 opCode = spv::OpSelect;
3444 spv::MissingFunctionality("translating integer mix to OpSelect");
3445 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003446 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003447 break;
3448 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003449 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003450 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003451 break;
3452 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003453 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003454 builder.promoteScalar(precision, operands[0], operands[2]);
3455 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003456 break;
3457
3458 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003459 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003460 break;
3461 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003462 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003463 break;
3464 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003465 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003466 break;
3467 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003468 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003469 break;
3470 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003471 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003472 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003473 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003474 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003475 libCall = spv::GLSLstd450InterpolateAtSample;
3476 break;
3477 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003478 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003479 libCall = spv::GLSLstd450InterpolateAtOffset;
3480 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003481 case glslang::EOpAddCarry:
3482 opCode = spv::OpIAddCarry;
3483 typeId = builder.makeStructResultType(typeId0, typeId0);
3484 consumedOperands = 2;
3485 break;
3486 case glslang::EOpSubBorrow:
3487 opCode = spv::OpISubBorrow;
3488 typeId = builder.makeStructResultType(typeId0, typeId0);
3489 consumedOperands = 2;
3490 break;
3491 case glslang::EOpUMulExtended:
3492 opCode = spv::OpUMulExtended;
3493 typeId = builder.makeStructResultType(typeId0, typeId0);
3494 consumedOperands = 2;
3495 break;
3496 case glslang::EOpIMulExtended:
3497 opCode = spv::OpSMulExtended;
3498 typeId = builder.makeStructResultType(typeId0, typeId0);
3499 consumedOperands = 2;
3500 break;
3501 case glslang::EOpBitfieldExtract:
3502 if (isUnsigned)
3503 opCode = spv::OpBitFieldUExtract;
3504 else
3505 opCode = spv::OpBitFieldSExtract;
3506 break;
3507 case glslang::EOpBitfieldInsert:
3508 opCode = spv::OpBitFieldInsert;
3509 break;
3510
3511 case glslang::EOpFma:
3512 libCall = spv::GLSLstd450Fma;
3513 break;
3514 case glslang::EOpFrexp:
3515 libCall = spv::GLSLstd450FrexpStruct;
3516 if (builder.getNumComponents(operands[0]) == 1)
3517 frexpIntType = builder.makeIntegerType(32, true);
3518 else
3519 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3520 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3521 consumedOperands = 1;
3522 break;
3523 case glslang::EOpLdexp:
3524 libCall = spv::GLSLstd450Ldexp;
3525 break;
3526
John Kessenich140f3df2015-06-26 16:58:36 -06003527 default:
3528 return 0;
3529 }
3530
3531 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003532 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003533 // Use an extended instruction from the standard library.
3534 // Construct the call arguments, without modifying the original operands vector.
3535 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3536 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003537 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003538 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003539 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003540 case 0:
3541 // should all be handled by visitAggregate and createNoArgOperation
3542 assert(0);
3543 return 0;
3544 case 1:
3545 // should all be handled by createUnaryOperation
3546 assert(0);
3547 return 0;
3548 case 2:
3549 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3550 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003551 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003552 // anything 3 or over doesn't have l-value operands, so all should be consumed
3553 assert(consumedOperands == operands.size());
3554 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003555 break;
3556 }
3557 }
3558
John Kessenich55e7d112015-11-15 21:33:39 -07003559 // Decode the return types that were structures
3560 switch (op) {
3561 case glslang::EOpAddCarry:
3562 case glslang::EOpSubBorrow:
3563 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3564 id = builder.createCompositeExtract(id, typeId0, 0);
3565 break;
3566 case glslang::EOpUMulExtended:
3567 case glslang::EOpIMulExtended:
3568 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3569 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3570 break;
3571 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003572 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003573 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3574 id = builder.createCompositeExtract(id, typeId0, 0);
3575 break;
3576 default:
3577 break;
3578 }
3579
John Kessenich32cfd492016-02-02 12:37:46 -07003580 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003581}
3582
3583// Intrinsics with no arguments, no return value, and no precision.
3584spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3585{
3586 // TODO: get the barrier operands correct
3587
3588 switch (op) {
3589 case glslang::EOpEmitVertex:
3590 builder.createNoResultOp(spv::OpEmitVertex);
3591 return 0;
3592 case glslang::EOpEndPrimitive:
3593 builder.createNoResultOp(spv::OpEndPrimitive);
3594 return 0;
3595 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003596 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3597 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003598 return 0;
3599 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003600 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003601 return 0;
3602 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003603 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003604 return 0;
3605 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003606 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003607 return 0;
3608 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003609 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003610 return 0;
3611 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003612 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003613 return 0;
3614 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003615 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003616 return 0;
3617 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003618 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003619 return 0;
3620 }
3621}
3622
3623spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3624{
John Kessenich2f273362015-07-18 22:34:27 -06003625 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003626 spv::Id id;
3627 if (symbolValues.end() != iter) {
3628 id = iter->second;
3629 return id;
3630 }
3631
3632 // it was not found, create it
3633 id = createSpvVariable(symbol);
3634 symbolValues[symbol->getId()] = id;
3635
3636 if (! symbol->getType().isStruct()) {
3637 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003638 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003639 if (symbol->getType().getQualifier().hasSpecConstantId())
3640 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003641 if (symbol->getQualifier().hasLocation())
3642 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3643 if (symbol->getQualifier().hasIndex())
3644 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3645 if (symbol->getQualifier().hasComponent())
3646 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3647 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003648 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003649 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003650 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003651 if (symbol->getQualifier().hasXfbBuffer())
3652 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3653 if (symbol->getQualifier().hasXfbOffset())
3654 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3655 }
3656 }
3657
John Kesseniche0b6cad2015-12-24 10:30:13 -07003658 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003659 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003660 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003661 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003662 }
John Kessenich140f3df2015-06-26 16:58:36 -06003663 if (symbol->getQualifier().hasSet())
3664 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003665 else if (IsDescriptorResource(symbol->getType())) {
3666 // default to 0
3667 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3668 }
John Kessenich140f3df2015-06-26 16:58:36 -06003669 if (symbol->getQualifier().hasBinding())
3670 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003671 if (symbol->getQualifier().hasAttachment())
3672 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003673 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003674 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003675 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003676 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003677 if (symbol->getQualifier().hasXfbBuffer())
3678 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3679 }
3680
Rex Xu1da878f2016-02-21 20:59:01 +08003681 if (symbol->getType().isImage()) {
3682 std::vector<spv::Decoration> memory;
3683 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3684 for (unsigned int i = 0; i < memory.size(); ++i)
3685 addDecoration(id, memory[i]);
3686 }
3687
John Kessenich140f3df2015-06-26 16:58:36 -06003688 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003689 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003690 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003691 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003692
John Kessenich140f3df2015-06-26 16:58:36 -06003693 return id;
3694}
3695
John Kessenich55e7d112015-11-15 21:33:39 -07003696// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003697void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3698{
3699 if (dec != spv::BadValue)
3700 builder.addDecoration(id, dec);
3701}
3702
John Kessenich55e7d112015-11-15 21:33:39 -07003703// If 'dec' is valid, add a one-operand decoration to an object
3704void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3705{
3706 if (dec != spv::BadValue)
3707 builder.addDecoration(id, dec, value);
3708}
3709
3710// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003711void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3712{
3713 if (dec != spv::BadValue)
3714 builder.addMemberDecoration(id, (unsigned)member, dec);
3715}
3716
John Kessenich92187592016-02-01 13:45:25 -07003717// If 'dec' is valid, add a one-operand decoration to a struct member
3718void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3719{
3720 if (dec != spv::BadValue)
3721 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3722}
3723
John Kessenich55e7d112015-11-15 21:33:39 -07003724// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003725// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003726//
3727// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3728//
3729// Recursively walk the nodes. The nodes form a tree whose leaves are
3730// regular constants, which themselves are trees that createSpvConstant()
3731// recursively walks. So, this function walks the "top" of the tree:
3732// - emit specialization constant-building instructions for specConstant
3733// - when running into a non-spec-constant, switch to createSpvConstant()
3734spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3735{
3736 assert(node.getQualifier().storage == glslang::EvqConst);
3737
John Kessenich6c292d32016-02-15 20:58:50 -07003738 if (! node.getQualifier().specConstant) {
3739 // hand off to the non-spec-constant path
3740 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3741 int nextConst = 0;
3742 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3743 nextConst, false);
3744 }
3745
3746 // We now know we have a specialization constant to build
3747
3748 if (node.getAsSymbolNode() && node.getQualifier().hasSpecConstantId()) {
3749 // this is a direct literal assigned to a layout(constant_id=) declaration
3750 int nextConst = 0;
3751 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3752 nextConst, true);
3753 } else {
3754 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3755 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3756 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3757 std::vector<spv::Id> dimConstId;
3758 for (int dim = 0; dim < 3; ++dim) {
3759 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3760 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3761 if (specConst)
3762 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3763 }
3764 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3765 } else {
3766 spv::MissingFunctionality("specialization-constant expression trees");
3767 return spv::NoResult;
3768 }
3769 }
John Kessenich55e7d112015-11-15 21:33:39 -07003770}
3771
John Kessenich140f3df2015-06-26 16:58:36 -06003772// Use 'consts' as the flattened glslang source of scalar constants to recursively
3773// build the aggregate SPIR-V constant.
3774//
3775// If there are not enough elements present in 'consts', 0 will be substituted;
3776// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3777//
John Kessenich55e7d112015-11-15 21:33:39 -07003778spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003779{
3780 // vector of constants for SPIR-V
3781 std::vector<spv::Id> spvConsts;
3782
3783 // Type is used for struct and array constants
3784 spv::Id typeId = convertGlslangToSpvType(glslangType);
3785
3786 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003787 glslang::TType elementType(glslangType, 0);
3788 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003789 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003790 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003791 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003792 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003793 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003794 } else if (glslangType.getStruct()) {
3795 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3796 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003797 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003798 } else if (glslangType.isVector()) {
3799 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3800 bool zero = nextConst >= consts.size();
3801 switch (glslangType.getBasicType()) {
3802 case glslang::EbtInt:
3803 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3804 break;
3805 case glslang::EbtUint:
3806 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3807 break;
3808 case glslang::EbtFloat:
3809 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3810 break;
3811 case glslang::EbtDouble:
3812 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3813 break;
3814 case glslang::EbtBool:
3815 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3816 break;
3817 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003818 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003819 break;
3820 }
3821 ++nextConst;
3822 }
3823 } else {
3824 // we have a non-aggregate (scalar) constant
3825 bool zero = nextConst >= consts.size();
3826 spv::Id scalar = 0;
3827 switch (glslangType.getBasicType()) {
3828 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003829 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003830 break;
3831 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003832 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003833 break;
3834 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003835 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003836 break;
3837 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003838 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003839 break;
3840 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003841 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003842 break;
3843 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003844 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003845 break;
3846 }
3847 ++nextConst;
3848 return scalar;
3849 }
3850
3851 return builder.makeCompositeConstant(typeId, spvConsts);
3852}
3853
John Kessenich7c1aa102015-10-15 13:29:11 -06003854// Return true if the node is a constant or symbol whose reading has no
3855// non-trivial observable cost or effect.
3856bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3857{
3858 // don't know what this is
3859 if (node == nullptr)
3860 return false;
3861
3862 // a constant is safe
3863 if (node->getAsConstantUnion() != nullptr)
3864 return true;
3865
3866 // not a symbol means non-trivial
3867 if (node->getAsSymbolNode() == nullptr)
3868 return false;
3869
3870 // a symbol, depends on what's being read
3871 switch (node->getType().getQualifier().storage) {
3872 case glslang::EvqTemporary:
3873 case glslang::EvqGlobal:
3874 case glslang::EvqIn:
3875 case glslang::EvqInOut:
3876 case glslang::EvqConst:
3877 case glslang::EvqConstReadOnly:
3878 case glslang::EvqUniform:
3879 return true;
3880 default:
3881 return false;
3882 }
3883}
3884
3885// A node is trivial if it is a single operation with no side effects.
3886// Error on the side of saying non-trivial.
3887// Return true if trivial.
3888bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3889{
3890 if (node == nullptr)
3891 return false;
3892
3893 // symbols and constants are trivial
3894 if (isTrivialLeaf(node))
3895 return true;
3896
3897 // otherwise, it needs to be a simple operation or one or two leaf nodes
3898
3899 // not a simple operation
3900 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3901 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3902 if (binaryNode == nullptr && unaryNode == nullptr)
3903 return false;
3904
3905 // not on leaf nodes
3906 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3907 return false;
3908
3909 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3910 return false;
3911 }
3912
3913 switch (node->getAsOperator()->getOp()) {
3914 case glslang::EOpLogicalNot:
3915 case glslang::EOpConvIntToBool:
3916 case glslang::EOpConvUintToBool:
3917 case glslang::EOpConvFloatToBool:
3918 case glslang::EOpConvDoubleToBool:
3919 case glslang::EOpEqual:
3920 case glslang::EOpNotEqual:
3921 case glslang::EOpLessThan:
3922 case glslang::EOpGreaterThan:
3923 case glslang::EOpLessThanEqual:
3924 case glslang::EOpGreaterThanEqual:
3925 case glslang::EOpIndexDirect:
3926 case glslang::EOpIndexDirectStruct:
3927 case glslang::EOpLogicalXor:
3928 case glslang::EOpAny:
3929 case glslang::EOpAll:
3930 return true;
3931 default:
3932 return false;
3933 }
3934}
3935
3936// Emit short-circuiting code, where 'right' is never evaluated unless
3937// the left side is true (for &&) or false (for ||).
3938spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3939{
3940 spv::Id boolTypeId = builder.makeBoolType();
3941
3942 // emit left operand
3943 builder.clearAccessChain();
3944 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08003945 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06003946
3947 // Operands to accumulate OpPhi operands
3948 std::vector<spv::Id> phiOperands;
3949 // accumulate left operand's phi information
3950 phiOperands.push_back(leftId);
3951 phiOperands.push_back(builder.getBuildPoint()->getId());
3952
3953 // Make the two kinds of operation symmetric with a "!"
3954 // || => emit "if (! left) result = right"
3955 // && => emit "if ( left) result = right"
3956 //
3957 // TODO: this runtime "not" for || could be avoided by adding functionality
3958 // to 'builder' to have an "else" without an "then"
3959 if (op == glslang::EOpLogicalOr)
3960 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3961
3962 // make an "if" based on the left value
3963 spv::Builder::If ifBuilder(leftId, builder);
3964
3965 // emit right operand as the "then" part of the "if"
3966 builder.clearAccessChain();
3967 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08003968 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06003969
3970 // accumulate left operand's phi information
3971 phiOperands.push_back(rightId);
3972 phiOperands.push_back(builder.getBuildPoint()->getId());
3973
3974 // finish the "if"
3975 ifBuilder.makeEndIf();
3976
3977 // phi together the two results
3978 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3979}
3980
John Kessenich140f3df2015-06-26 16:58:36 -06003981}; // end anonymous namespace
3982
3983namespace glslang {
3984
John Kessenich68d78fd2015-07-12 19:28:10 -06003985void GetSpirvVersion(std::string& version)
3986{
John Kessenich9e55f632015-07-15 10:03:39 -06003987 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003988 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003989 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003990 version = buf;
3991}
3992
John Kessenich140f3df2015-06-26 16:58:36 -06003993// Write SPIR-V out to a binary file
3994void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3995{
3996 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003997 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003998 for (int i = 0; i < (int)spirv.size(); ++i) {
3999 unsigned int word = spirv[i];
4000 out.write((const char*)&word, 4);
4001 }
4002 out.close();
4003}
4004
4005//
4006// Set up the glslang traversal
4007//
4008void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4009{
4010 TIntermNode* root = intermediate.getTreeRoot();
4011
4012 if (root == 0)
4013 return;
4014
4015 glslang::GetThreadPoolAllocator().push();
4016
4017 TGlslangToSpvTraverser it(&intermediate);
4018
4019 root->traverse(&it);
4020
4021 it.dumpSpv(spirv);
4022
4023 glslang::GetThreadPoolAllocator().pop();
4024}
4025
4026}; // end namespace glslang