blob: 81509975622a37d3aeff3ca447aa77fdf640ba5f [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
2//Copyright (C) 2014 LunarG, Inc.
3//
4//All rights reserved.
5//
6//Redistribution and use in source and binary forms, with or without
7//modification, are permitted provided that the following conditions
8//are met:
9//
10// Redistributions of source code must retain the above copyright
11// notice, this list of conditions and the following disclaimer.
12//
13// Redistributions in binary form must reproduce the above
14// copyright notice, this list of conditions and the following
15// disclaimer in the documentation and/or other materials provided
16// with the distribution.
17//
18// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
19// contributors may be used to endorse or promote products derived
20// from this software without specific prior written permission.
21//
22//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
32//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33//POSSIBILITY OF SUCH DAMAGE.
34
35//
36// Author: John Kessenich, LunarG
37//
38// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
46 #include "GLSL.std.450.h"
47}
John Kessenich140f3df2015-06-26 16:58:36 -060048
49// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020050#include "../glslang/MachineIndependent/localintermediate.h"
51#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060052#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060053
54#include <string>
55#include <map>
56#include <list>
57#include <vector>
58#include <stack>
59#include <fstream>
60
61namespace {
62
John Kessenich55e7d112015-11-15 21:33:39 -070063// For low-order part of the generator's magic number. Bump up
64// when there is a change in the style (e.g., if SSA form changes,
65// or a different instruction sequence to do something gets used).
66const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060067
68//
69// The main holder of information for translating glslang to SPIR-V.
70//
71// Derives from the AST walking base class.
72//
73class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
74public:
75 TGlslangToSpvTraverser(const glslang::TIntermediate*);
76 virtual ~TGlslangToSpvTraverser();
77
78 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
79 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
80 void visitConstantUnion(glslang::TIntermConstantUnion*);
81 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
82 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
83 void visitSymbol(glslang::TIntermSymbol* symbol);
84 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
85 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
86 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
87
John Kessenich7ba63412015-12-20 17:37:07 -070088 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -060089
90protected:
John Kessenich5e801132016-02-15 11:09:46 -070091 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
John Kessenich92187592016-02-01 13:45:25 -070092 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable);
John Kessenich5d0fa972016-02-15 11:57:00 -070093 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -060094 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
95 spv::Id getSampledType(const glslang::TSampler&);
96 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -070097 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich32cfd492016-02-02 12:37:46 -070098 spv::Id accessChainLoad(const glslang::TType& type);
John Kessenichf85e8062015-12-19 13:57:10 -070099 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700100 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
101 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
102 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 -0600103
104 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
105 void makeFunctions(const glslang::TIntermSequence&);
106 void makeGlobalInitializers(const glslang::TIntermSequence&);
107 void visitFunctions(const glslang::TIntermSequence&);
108 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800109 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600110 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
111 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600112 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
113
114 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 -0700115 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800116 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 -0700117 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600118 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
119 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800120 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 -0600121 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 -0600122 spv::Id createNoArgOperation(glslang::TOperator op);
123 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
124 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700125 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600126 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700127 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
John Kessenich55e7d112015-11-15 21:33:39 -0700128 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
129 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600130 bool isTrivialLeaf(const glslang::TIntermTyped* node);
131 bool isTrivial(const glslang::TIntermTyped* node);
132 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600133
134 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700135 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600136 int sequenceDepth;
137
138 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
139 spv::Builder builder;
140 bool inMain;
141 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700142 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 -0700143 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600144 const glslang::TIntermediate* glslangIntermediate;
145 spv::Id stdBuiltins;
146
John Kessenich2f273362015-07-18 22:34:27 -0600147 std::unordered_map<int, spv::Id> symbolValues;
148 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
149 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700150 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600151 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 -0600152 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600153};
154
155//
156// Helper functions for translating glslang representations to SPIR-V enumerants.
157//
158
159// Translate glslang profile to SPIR-V source language.
160spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
161{
162 switch (profile) {
163 case ENoProfile:
164 case ECoreProfile:
165 case ECompatibilityProfile:
166 return spv::SourceLanguageGLSL;
167 case EEsProfile:
168 return spv::SourceLanguageESSL;
169 default:
170 return spv::SourceLanguageUnknown;
171 }
172}
173
174// Translate glslang language (stage) to SPIR-V execution model.
175spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
176{
177 switch (stage) {
178 case EShLangVertex: return spv::ExecutionModelVertex;
179 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
180 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
181 case EShLangGeometry: return spv::ExecutionModelGeometry;
182 case EShLangFragment: return spv::ExecutionModelFragment;
183 case EShLangCompute: return spv::ExecutionModelGLCompute;
184 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700185 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600186 return spv::ExecutionModelFragment;
187 }
188}
189
190// Translate glslang type to SPIR-V storage class.
191spv::StorageClass TranslateStorageClass(const glslang::TType& type)
192{
193 if (type.getQualifier().isPipeInput())
194 return spv::StorageClassInput;
195 else if (type.getQualifier().isPipeOutput())
196 return spv::StorageClassOutput;
197 else if (type.getQualifier().isUniformOrBuffer()) {
198 if (type.getBasicType() == glslang::EbtBlock)
199 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800200 else if (type.getBasicType() == glslang::EbtAtomicUint)
201 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600202 else
203 return spv::StorageClassUniformConstant;
204 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
205 } else {
206 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700207 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
208 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600209 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
210 case glslang::EvqTemporary: return spv::StorageClassFunction;
211 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700212 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600213 return spv::StorageClassFunction;
214 }
215 }
216}
217
218// Translate glslang sampler type to SPIR-V dimensionality.
219spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
220{
221 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700222 case glslang::Esd1D: return spv::Dim1D;
223 case glslang::Esd2D: return spv::Dim2D;
224 case glslang::Esd3D: return spv::Dim3D;
225 case glslang::EsdCube: return spv::DimCube;
226 case glslang::EsdRect: return spv::DimRect;
227 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich140f3df2015-06-26 16:58:36 -0600228 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700229 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600230 return spv::Dim2D;
231 }
232}
233
234// Translate glslang type to SPIR-V precision decorations.
235spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
236{
237 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700238 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600239 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600240 default:
241 return spv::NoPrecision;
242 }
243}
244
245// Translate glslang type to SPIR-V block decorations.
246spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
247{
248 if (type.getBasicType() == glslang::EbtBlock) {
249 switch (type.getQualifier().storage) {
250 case glslang::EvqUniform: return spv::DecorationBlock;
251 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
252 case glslang::EvqVaryingIn: return spv::DecorationBlock;
253 case glslang::EvqVaryingOut: return spv::DecorationBlock;
254 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700255 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600256 break;
257 }
258 }
259
260 return (spv::Decoration)spv::BadValue;
261}
262
263// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700264spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600265{
266 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700267 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600268 case glslang::ElmRowMajor:
269 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700270 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600271 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700272 default:
273 // opaque layouts don't need a majorness
274 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600275 }
276 } else {
277 switch (type.getBasicType()) {
278 default:
279 return (spv::Decoration)spv::BadValue;
280 break;
281 case glslang::EbtBlock:
282 switch (type.getQualifier().storage) {
283 case glslang::EvqUniform:
284 case glslang::EvqBuffer:
285 switch (type.getQualifier().layoutPacking) {
286 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600287 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
288 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600289 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600290 }
291 case glslang::EvqVaryingIn:
292 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700293 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600294 return (spv::Decoration)spv::BadValue;
295 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700296 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600297 return (spv::Decoration)spv::BadValue;
298 }
299 }
300 }
301}
302
303// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700304// Returns spv::Decoration(spv::BadValue) when no decoration
305// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700306spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600307{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700308 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700309 // Smooth decoration doesn't exist in SPIR-V 1.0
310 return (spv::Decoration)spv::BadValue;
311 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700312 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700313 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700314 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600315 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700316 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600317 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700318 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600319 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700320 else if (qualifier.sample) {
321 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600322 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700323 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600324 return (spv::Decoration)spv::BadValue;
325}
326
John Kessenich92187592016-02-01 13:45:25 -0700327// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700328spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600329{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700330 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600331 return spv::DecorationInvariant;
332 else
333 return (spv::Decoration)spv::BadValue;
334}
335
336// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700337spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600338{
339 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700340 case glslang::EbvPointSize:
341 switch (glslangIntermediate->getStage()) {
342 case EShLangGeometry:
343 builder.addCapability(spv::CapabilityGeometryPointSize);
344 break;
345 case EShLangTessControl:
346 case EShLangTessEvaluation:
347 builder.addCapability(spv::CapabilityTessellationPointSize);
348 break;
349 }
350 return spv::BuiltInPointSize;
351
352 case glslang::EbvClipDistance:
353 builder.addCapability(spv::CapabilityClipDistance);
354 return spv::BuiltInClipDistance;
355
356 case glslang::EbvCullDistance:
357 builder.addCapability(spv::CapabilityCullDistance);
358 return spv::BuiltInCullDistance;
359
360 case glslang::EbvViewportIndex:
361 // TODO: builder.addCapability(spv::CapabilityMultiViewport);
362 return spv::BuiltInViewportIndex;
363
John Kessenich5e801132016-02-15 11:09:46 -0700364 case glslang::EbvSampleId:
365 builder.addCapability(spv::CapabilitySampleRateShading);
366 return spv::BuiltInSampleId;
367
368 case glslang::EbvSamplePosition:
369 builder.addCapability(spv::CapabilitySampleRateShading);
370 return spv::BuiltInSamplePosition;
371
372 case glslang::EbvSampleMask:
373 builder.addCapability(spv::CapabilitySampleRateShading);
374 return spv::BuiltInSampleMask;
375
John Kessenich140f3df2015-06-26 16:58:36 -0600376 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600377 case glslang::EbvVertexId: return spv::BuiltInVertexId;
378 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenichda581a22015-10-14 14:10:30 -0600379 case glslang::EbvBaseVertex:
380 case glslang::EbvBaseInstance:
381 case glslang::EbvDrawId:
382 // TODO: Add SPIR-V builtin ID.
383 spv::MissingFunctionality("Draw parameters");
384 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600385 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
386 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
387 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600388 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
389 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
390 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
391 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
392 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
393 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
394 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600395 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
396 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
397 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
398 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
399 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
400 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
401 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
402 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
403 default: return (spv::BuiltIn)spv::BadValue;
404 }
405}
406
Rex Xufc618912015-09-09 16:42:49 +0800407// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700408spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800409{
410 assert(type.getBasicType() == glslang::EbtSampler);
411
John Kessenich5d0fa972016-02-15 11:57:00 -0700412 // Check for capabilities
413 switch (type.getQualifier().layoutFormat) {
414 case glslang::ElfRg32f:
415 case glslang::ElfRg16f:
416 case glslang::ElfR11fG11fB10f:
417 case glslang::ElfR16f:
418 case glslang::ElfRgba16:
419 case glslang::ElfRgb10A2:
420 case glslang::ElfRg16:
421 case glslang::ElfRg8:
422 case glslang::ElfR16:
423 case glslang::ElfR8:
424 case glslang::ElfRgba16Snorm:
425 case glslang::ElfRg16Snorm:
426 case glslang::ElfRg8Snorm:
427 case glslang::ElfR16Snorm:
428 case glslang::ElfR8Snorm:
429
430 case glslang::ElfRg32i:
431 case glslang::ElfRg16i:
432 case glslang::ElfRg8i:
433 case glslang::ElfR16i:
434 case glslang::ElfR8i:
435
436 case glslang::ElfRgb10a2ui:
437 case glslang::ElfRg32ui:
438 case glslang::ElfRg16ui:
439 case glslang::ElfRg8ui:
440 case glslang::ElfR16ui:
441 case glslang::ElfR8ui:
442 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
443 break;
444
445 default:
446 break;
447 }
448
449 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800450 switch (type.getQualifier().layoutFormat) {
451 case glslang::ElfNone: return spv::ImageFormatUnknown;
452 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
453 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
454 case glslang::ElfR32f: return spv::ImageFormatR32f;
455 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
456 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
457 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
458 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
459 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
460 case glslang::ElfR16f: return spv::ImageFormatR16f;
461 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
462 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
463 case glslang::ElfRg16: return spv::ImageFormatRg16;
464 case glslang::ElfRg8: return spv::ImageFormatRg8;
465 case glslang::ElfR16: return spv::ImageFormatR16;
466 case glslang::ElfR8: return spv::ImageFormatR8;
467 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
468 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
469 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
470 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
471 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
472 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
473 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
474 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
475 case glslang::ElfR32i: return spv::ImageFormatR32i;
476 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
477 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
478 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
479 case glslang::ElfR16i: return spv::ImageFormatR16i;
480 case glslang::ElfR8i: return spv::ImageFormatR8i;
481 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
482 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
483 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
484 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
485 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
486 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
487 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
488 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
489 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
490 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
491 default: return (spv::ImageFormat)spv::BadValue;
492 }
493}
494
John Kesseniche0b6cad2015-12-24 10:30:13 -0700495void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
496{
497 if (child.layoutMatrix == glslang::ElmNone)
498 child.layoutMatrix = parent.layoutMatrix;
499
500 if (parent.invariant)
501 child.invariant = true;
502 if (parent.nopersp)
503 child.nopersp = true;
504 if (parent.flat)
505 child.flat = true;
506 if (parent.centroid)
507 child.centroid = true;
508 if (parent.patch)
509 child.patch = true;
510 if (parent.sample)
511 child.sample = true;
John Kessenich7b9fa252016-01-21 18:56:57 -0700512
513 child.layoutLocation = parent.layoutLocation;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700514}
515
516bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
517{
John Kessenich7b9fa252016-01-21 18:56:57 -0700518 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700519 // - struct members can inherit from a struct declaration
520 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
521 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700522 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700523}
524
John Kessenich140f3df2015-06-26 16:58:36 -0600525//
526// Implement the TGlslangToSpvTraverser class.
527//
528
529TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
530 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700531 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600532 inMain(false), mainTerminated(false), linkageOnly(false),
533 glslangIntermediate(glslangIntermediate)
534{
535 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
536
537 builder.clearAccessChain();
538 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
539 stdBuiltins = builder.import("GLSL.std.450");
540 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
541 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700542 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600543
544 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600545 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
546 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600547 builder.addSourceExtension(it->c_str());
548
549 // Add the top-level modes for this shader.
550
John Kessenich92187592016-02-01 13:45:25 -0700551 if (glslangIntermediate->getXfbMode()) {
552 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600553 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700554 }
John Kessenich140f3df2015-06-26 16:58:36 -0600555
556 unsigned int mode;
557 switch (glslangIntermediate->getStage()) {
558 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600559 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600560 break;
561
562 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600563 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600564 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
565 break;
566
567 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600568 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600569 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700570 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
571 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
572 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600573 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600574 }
575 if (mode != spv::BadValue)
576 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
577
John Kesseniche6903322015-10-13 16:29:02 -0600578 switch (glslangIntermediate->getVertexSpacing()) {
579 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
580 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
581 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
582 default: mode = spv::BadValue; break;
583 }
584 if (mode != spv::BadValue)
585 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
586
587 switch (glslangIntermediate->getVertexOrder()) {
588 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
589 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
590 default: mode = spv::BadValue; break;
591 }
592 if (mode != spv::BadValue)
593 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
594
595 if (glslangIntermediate->getPointMode())
596 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600597 break;
598
599 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600600 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600601 switch (glslangIntermediate->getInputPrimitive()) {
602 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
603 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
604 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700605 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600606 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
607 default: mode = spv::BadValue; break;
608 }
609 if (mode != spv::BadValue)
610 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600611
John Kessenich140f3df2015-06-26 16:58:36 -0600612 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
613
614 switch (glslangIntermediate->getOutputPrimitive()) {
615 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
616 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
617 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
618 default: mode = spv::BadValue; break;
619 }
620 if (mode != spv::BadValue)
621 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
622 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
623 break;
624
625 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600626 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600627 if (glslangIntermediate->getPixelCenterInteger())
628 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600629
John Kessenich140f3df2015-06-26 16:58:36 -0600630 if (glslangIntermediate->getOriginUpperLeft())
631 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600632 else
633 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600634
635 if (glslangIntermediate->getEarlyFragmentTests())
636 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
637
638 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600639 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
640 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
641 default: mode = spv::BadValue; break;
642 }
643 if (mode != spv::BadValue)
644 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
645
646 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
647 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600648 break;
649
650 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600651 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600652 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
653 glslangIntermediate->getLocalSize(1),
654 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600655 break;
656
657 default:
658 break;
659 }
660
661}
662
John Kessenich7ba63412015-12-20 17:37:07 -0700663// Finish everything and dump
664void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
665{
666 // finish off the entry-point SPV instruction by adding the Input/Output <id>
667 for (auto it : iOSet)
668 entryPoint->addIdOperand(it);
669
670 builder.dump(out);
671}
672
John Kessenich140f3df2015-06-26 16:58:36 -0600673TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
674{
675 if (! mainTerminated) {
676 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
677 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600678 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600679 }
680}
681
682//
683// Implement the traversal functions.
684//
685// Return true from interior nodes to have the external traversal
686// continue on to children. Return false if children were
687// already processed.
688//
689
690//
691// Symbols can turn into
692// - uniform/input reads
693// - output writes
694// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
695// - something simple that degenerates into the last bullet
696//
697void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
698{
699 // getSymbolId() will set up all the IO decorations on the first call.
700 // Formal function parameters were mapped during makeFunctions().
701 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700702
703 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
704 if (builder.isPointer(id)) {
705 spv::StorageClass sc = builder.getStorageClass(id);
706 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
707 iOSet.insert(id);
708 }
709
710 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich140f3df2015-06-26 16:58:36 -0600711 if (! linkageOnly) {
712 // Prepare to generate code for the access
713
714 // L-value chains will be computed left to right. We're on the symbol now,
715 // which is the left-most part of the access chain, so now is "clear" time,
716 // followed by setting the base.
717 builder.clearAccessChain();
718
719 // For now, we consider all user variables as being in memory, so they are pointers,
720 // except for "const in" arguments to a function, which are an intermediate object.
721 // See comments in handleUserFunctionCall().
722 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
723 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
724 builder.setAccessChainRValue(id);
725 else
726 builder.setAccessChainLValue(id);
727 }
728}
729
730bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
731{
732 // First, handle special cases
733 switch (node->getOp()) {
734 case glslang::EOpAssign:
735 case glslang::EOpAddAssign:
736 case glslang::EOpSubAssign:
737 case glslang::EOpMulAssign:
738 case glslang::EOpVectorTimesMatrixAssign:
739 case glslang::EOpVectorTimesScalarAssign:
740 case glslang::EOpMatrixTimesScalarAssign:
741 case glslang::EOpMatrixTimesMatrixAssign:
742 case glslang::EOpDivAssign:
743 case glslang::EOpModAssign:
744 case glslang::EOpAndAssign:
745 case glslang::EOpInclusiveOrAssign:
746 case glslang::EOpExclusiveOrAssign:
747 case glslang::EOpLeftShiftAssign:
748 case glslang::EOpRightShiftAssign:
749 // A bin-op assign "a += b" means the same thing as "a = a + b"
750 // where a is evaluated before b. For a simple assignment, GLSL
751 // says to evaluate the left before the right. So, always, left
752 // node then right node.
753 {
754 // get the left l-value, save it away
755 builder.clearAccessChain();
756 node->getLeft()->traverse(this);
757 spv::Builder::AccessChain lValue = builder.getAccessChain();
758
759 // evaluate the right
760 builder.clearAccessChain();
761 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700762 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600763
764 if (node->getOp() != glslang::EOpAssign) {
765 // the left is also an r-value
766 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700767 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600768
769 // do the operation
770 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
771 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
772 node->getType().getBasicType());
773
774 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700775 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600776 }
777
778 // store the result
779 builder.setAccessChain(lValue);
780 builder.accessChainStore(rValue);
781
782 // assignments are expressions having an rValue after they are evaluated...
783 builder.clearAccessChain();
784 builder.setAccessChainRValue(rValue);
785 }
786 return false;
787 case glslang::EOpIndexDirect:
788 case glslang::EOpIndexDirectStruct:
789 {
790 // Get the left part of the access chain.
791 node->getLeft()->traverse(this);
792
793 // Add the next element in the chain
794
John Kessenich55e7d112015-11-15 21:33:39 -0700795 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600796 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
797 // This may be, e.g., an anonymous block-member selection, which generally need
798 // index remapping due to hidden members in anonymous blocks.
799 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700800 assert(remapper.size() > 0);
801 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600802 }
803
804 if (! node->getLeft()->getType().isArray() &&
805 node->getLeft()->getType().isVector() &&
806 node->getOp() == glslang::EOpIndexDirect) {
807 // This is essentially a hard-coded vector swizzle of size 1,
808 // so short circuit the access-chain stuff with a swizzle.
809 std::vector<unsigned> swizzle;
810 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600811 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600812 } else {
813 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600814 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600815 }
816 }
817 return false;
818 case glslang::EOpIndexIndirect:
819 {
820 // Structure or array or vector indirection.
821 // Will use native SPIR-V access-chain for struct and array indirection;
822 // matrices are arrays of vectors, so will also work for a matrix.
823 // Will use the access chain's 'component' for variable index into a vector.
824
825 // This adapter is building access chains left to right.
826 // Set up the access chain to the left.
827 node->getLeft()->traverse(this);
828
829 // save it so that computing the right side doesn't trash it
830 spv::Builder::AccessChain partial = builder.getAccessChain();
831
832 // compute the next index in the chain
833 builder.clearAccessChain();
834 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700835 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600836
837 // restore the saved access chain
838 builder.setAccessChain(partial);
839
840 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600841 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600842 else
John Kessenichfa668da2015-09-13 14:46:30 -0600843 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600844 }
845 return false;
846 case glslang::EOpVectorSwizzle:
847 {
848 node->getLeft()->traverse(this);
849 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
850 std::vector<unsigned> swizzle;
851 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
852 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600853 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600854 }
855 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600856 case glslang::EOpLogicalOr:
857 case glslang::EOpLogicalAnd:
858 {
859
860 // These may require short circuiting, but can sometimes be done as straight
861 // binary operations. The right operand must be short circuited if it has
862 // side effects, and should probably be if it is complex.
863 if (isTrivial(node->getRight()->getAsTyped()))
864 break; // handle below as a normal binary operation
865 // otherwise, we need to do dynamic short circuiting on the right operand
866 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
867 builder.clearAccessChain();
868 builder.setAccessChainRValue(result);
869 }
870 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600871 default:
872 break;
873 }
874
875 // Assume generic binary op...
876
John Kessenich32cfd492016-02-02 12:37:46 -0700877 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600878 builder.clearAccessChain();
879 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700880 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600881
John Kessenich32cfd492016-02-02 12:37:46 -0700882 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600883 builder.clearAccessChain();
884 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700885 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600886
John Kessenich32cfd492016-02-02 12:37:46 -0700887 // get result
888 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
889 convertGlslangToSpvType(node->getType()), left, right,
890 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600891
John Kessenich50e57562015-12-21 21:21:11 -0700892 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600893 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700894 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700895 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600896 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600897 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600898 return false;
899 }
John Kessenich140f3df2015-06-26 16:58:36 -0600900}
901
902bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
903{
John Kessenichfc51d282015-08-19 13:34:18 -0600904 spv::Id result = spv::NoResult;
905
906 // try texturing first
907 result = createImageTextureFunctionCall(node);
908 if (result != spv::NoResult) {
909 builder.clearAccessChain();
910 builder.setAccessChainRValue(result);
911
912 return false; // done with this node
913 }
914
915 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600916
917 if (node->getOp() == glslang::EOpArrayLength) {
918 // Quite special; won't want to evaluate the operand.
919
920 // Normal .length() would have been constant folded by the front-end.
921 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600922 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600923 assert(node->getOperand()->getType().isRuntimeSizedArray());
924 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
925 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600926 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
927 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600928
929 builder.clearAccessChain();
930 builder.setAccessChainRValue(length);
931
932 return false;
933 }
934
John Kessenichfc51d282015-08-19 13:34:18 -0600935 // Start by evaluating the operand
936
John Kessenich140f3df2015-06-26 16:58:36 -0600937 builder.clearAccessChain();
938 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800939
Rex Xufc618912015-09-09 16:42:49 +0800940 spv::Id operand = spv::NoResult;
941
942 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
943 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800944 node->getOp() == glslang::EOpAtomicCounter ||
945 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800946 operand = builder.accessChainGetLValue(); // Special case l-value operands
947 else
John Kessenich32cfd492016-02-02 12:37:46 -0700948 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600949
950 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
951
952 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600953 if (! result)
954 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600955
956 // if not, then possibly an operation
957 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700958 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600959
960 if (result) {
961 builder.clearAccessChain();
962 builder.setAccessChainRValue(result);
963
964 return false; // done with this node
965 }
966
967 // it must be a special case, check...
968 switch (node->getOp()) {
969 case glslang::EOpPostIncrement:
970 case glslang::EOpPostDecrement:
971 case glslang::EOpPreIncrement:
972 case glslang::EOpPreDecrement:
973 {
974 // we need the integer value "1" or the floating point "1.0" to add/subtract
975 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
976 builder.makeFloatConstant(1.0F) :
977 builder.makeIntConstant(1);
978 glslang::TOperator op;
979 if (node->getOp() == glslang::EOpPreIncrement ||
980 node->getOp() == glslang::EOpPostIncrement)
981 op = glslang::EOpAdd;
982 else
983 op = glslang::EOpSub;
984
985 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
986 convertGlslangToSpvType(node->getType()), operand, one,
987 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -0700988 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600989
990 // The result of operation is always stored, but conditionally the
991 // consumed result. The consumed result is always an r-value.
992 builder.accessChainStore(result);
993 builder.clearAccessChain();
994 if (node->getOp() == glslang::EOpPreIncrement ||
995 node->getOp() == glslang::EOpPreDecrement)
996 builder.setAccessChainRValue(result);
997 else
998 builder.setAccessChainRValue(operand);
999 }
1000
1001 return false;
1002
1003 case glslang::EOpEmitStreamVertex:
1004 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1005 return false;
1006 case glslang::EOpEndStreamPrimitive:
1007 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1008 return false;
1009
1010 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001011 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001012 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001013 }
John Kessenich140f3df2015-06-26 16:58:36 -06001014}
1015
1016bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1017{
John Kessenichfc51d282015-08-19 13:34:18 -06001018 spv::Id result = spv::NoResult;
1019
1020 // try texturing
1021 result = createImageTextureFunctionCall(node);
1022 if (result != spv::NoResult) {
1023 builder.clearAccessChain();
1024 builder.setAccessChainRValue(result);
1025
1026 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001027 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001028 // "imageStore" is a special case, which has no result
1029 return false;
1030 }
John Kessenichfc51d282015-08-19 13:34:18 -06001031
John Kessenich140f3df2015-06-26 16:58:36 -06001032 glslang::TOperator binOp = glslang::EOpNull;
1033 bool reduceComparison = true;
1034 bool isMatrix = false;
1035 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001036 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001037
1038 assert(node->getOp());
1039
1040 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1041
1042 switch (node->getOp()) {
1043 case glslang::EOpSequence:
1044 {
1045 if (preVisit)
1046 ++sequenceDepth;
1047 else
1048 --sequenceDepth;
1049
1050 if (sequenceDepth == 1) {
1051 // If this is the parent node of all the functions, we want to see them
1052 // early, so all call points have actual SPIR-V functions to reference.
1053 // In all cases, still let the traverser visit the children for us.
1054 makeFunctions(node->getAsAggregate()->getSequence());
1055
1056 // Also, we want all globals initializers to go into the entry of main(), before
1057 // anything else gets there, so visit out of order, doing them all now.
1058 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1059
1060 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1061 // so do them manually.
1062 visitFunctions(node->getAsAggregate()->getSequence());
1063
1064 return false;
1065 }
1066
1067 return true;
1068 }
1069 case glslang::EOpLinkerObjects:
1070 {
1071 if (visit == glslang::EvPreVisit)
1072 linkageOnly = true;
1073 else
1074 linkageOnly = false;
1075
1076 return true;
1077 }
1078 case glslang::EOpComma:
1079 {
1080 // processing from left to right naturally leaves the right-most
1081 // lying around in the access chain
1082 glslang::TIntermSequence& glslangOperands = node->getSequence();
1083 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1084 glslangOperands[i]->traverse(this);
1085
1086 return false;
1087 }
1088 case glslang::EOpFunction:
1089 if (visit == glslang::EvPreVisit) {
1090 if (isShaderEntrypoint(node)) {
1091 inMain = true;
1092 builder.setBuildPoint(shaderEntry->getLastBlock());
1093 } else {
1094 handleFunctionEntry(node);
1095 }
1096 } else {
1097 if (inMain)
1098 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001099 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001100 inMain = false;
1101 }
1102
1103 return true;
1104 case glslang::EOpParameters:
1105 // Parameters will have been consumed by EOpFunction processing, but not
1106 // the body, so we still visited the function node's children, making this
1107 // child redundant.
1108 return false;
1109 case glslang::EOpFunctionCall:
1110 {
1111 if (node->isUserDefined())
1112 result = handleUserFunctionCall(node);
John Kessenich55e7d112015-11-15 21:33:39 -07001113 assert(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001114 builder.clearAccessChain();
1115 builder.setAccessChainRValue(result);
1116
1117 return false;
1118 }
1119 case glslang::EOpConstructMat2x2:
1120 case glslang::EOpConstructMat2x3:
1121 case glslang::EOpConstructMat2x4:
1122 case glslang::EOpConstructMat3x2:
1123 case glslang::EOpConstructMat3x3:
1124 case glslang::EOpConstructMat3x4:
1125 case glslang::EOpConstructMat4x2:
1126 case glslang::EOpConstructMat4x3:
1127 case glslang::EOpConstructMat4x4:
1128 case glslang::EOpConstructDMat2x2:
1129 case glslang::EOpConstructDMat2x3:
1130 case glslang::EOpConstructDMat2x4:
1131 case glslang::EOpConstructDMat3x2:
1132 case glslang::EOpConstructDMat3x3:
1133 case glslang::EOpConstructDMat3x4:
1134 case glslang::EOpConstructDMat4x2:
1135 case glslang::EOpConstructDMat4x3:
1136 case glslang::EOpConstructDMat4x4:
1137 isMatrix = true;
1138 // fall through
1139 case glslang::EOpConstructFloat:
1140 case glslang::EOpConstructVec2:
1141 case glslang::EOpConstructVec3:
1142 case glslang::EOpConstructVec4:
1143 case glslang::EOpConstructDouble:
1144 case glslang::EOpConstructDVec2:
1145 case glslang::EOpConstructDVec3:
1146 case glslang::EOpConstructDVec4:
1147 case glslang::EOpConstructBool:
1148 case glslang::EOpConstructBVec2:
1149 case glslang::EOpConstructBVec3:
1150 case glslang::EOpConstructBVec4:
1151 case glslang::EOpConstructInt:
1152 case glslang::EOpConstructIVec2:
1153 case glslang::EOpConstructIVec3:
1154 case glslang::EOpConstructIVec4:
1155 case glslang::EOpConstructUint:
1156 case glslang::EOpConstructUVec2:
1157 case glslang::EOpConstructUVec3:
1158 case glslang::EOpConstructUVec4:
1159 case glslang::EOpConstructStruct:
1160 {
1161 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001162 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001163 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1164 spv::Id constructed;
1165 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1166 std::vector<spv::Id> constituents;
1167 for (int c = 0; c < (int)arguments.size(); ++c)
1168 constituents.push_back(arguments[c]);
1169 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001170 } else if (isMatrix)
1171 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1172 else
1173 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001174
1175 builder.clearAccessChain();
1176 builder.setAccessChainRValue(constructed);
1177
1178 return false;
1179 }
1180
1181 // These six are component-wise compares with component-wise results.
1182 // Forward on to createBinaryOperation(), requesting a vector result.
1183 case glslang::EOpLessThan:
1184 case glslang::EOpGreaterThan:
1185 case glslang::EOpLessThanEqual:
1186 case glslang::EOpGreaterThanEqual:
1187 case glslang::EOpVectorEqual:
1188 case glslang::EOpVectorNotEqual:
1189 {
1190 // Map the operation to a binary
1191 binOp = node->getOp();
1192 reduceComparison = false;
1193 switch (node->getOp()) {
1194 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1195 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1196 default: binOp = node->getOp(); break;
1197 }
1198
1199 break;
1200 }
1201 case glslang::EOpMul:
1202 // compontent-wise matrix multiply
1203 binOp = glslang::EOpMul;
1204 break;
1205 case glslang::EOpOuterProduct:
1206 // two vectors multiplied to make a matrix
1207 binOp = glslang::EOpOuterProduct;
1208 break;
1209 case glslang::EOpDot:
1210 {
1211 // for scalar dot product, use multiply
1212 glslang::TIntermSequence& glslangOperands = node->getSequence();
1213 if (! glslangOperands[0]->getAsTyped()->isVector())
1214 binOp = glslang::EOpMul;
1215 break;
1216 }
1217 case glslang::EOpMod:
1218 // when an aggregate, this is the floating-point mod built-in function,
1219 // which can be emitted by the one in createBinaryOperation()
1220 binOp = glslang::EOpMod;
1221 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001222 case glslang::EOpEmitVertex:
1223 case glslang::EOpEndPrimitive:
1224 case glslang::EOpBarrier:
1225 case glslang::EOpMemoryBarrier:
1226 case glslang::EOpMemoryBarrierAtomicCounter:
1227 case glslang::EOpMemoryBarrierBuffer:
1228 case glslang::EOpMemoryBarrierImage:
1229 case glslang::EOpMemoryBarrierShared:
1230 case glslang::EOpGroupMemoryBarrier:
1231 noReturnValue = true;
1232 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1233 break;
1234
John Kessenich426394d2015-07-23 10:22:48 -06001235 case glslang::EOpAtomicAdd:
1236 case glslang::EOpAtomicMin:
1237 case glslang::EOpAtomicMax:
1238 case glslang::EOpAtomicAnd:
1239 case glslang::EOpAtomicOr:
1240 case glslang::EOpAtomicXor:
1241 case glslang::EOpAtomicExchange:
1242 case glslang::EOpAtomicCompSwap:
1243 atomic = true;
1244 break;
1245
John Kessenich140f3df2015-06-26 16:58:36 -06001246 default:
1247 break;
1248 }
1249
1250 //
1251 // See if it maps to a regular operation.
1252 //
John Kessenich140f3df2015-06-26 16:58:36 -06001253 if (binOp != glslang::EOpNull) {
1254 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1255 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1256 assert(left && right);
1257
1258 builder.clearAccessChain();
1259 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001260 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001261
1262 builder.clearAccessChain();
1263 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001264 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001265
1266 result = createBinaryOperation(binOp, precision,
1267 convertGlslangToSpvType(node->getType()), leftId, rightId,
1268 left->getType().getBasicType(), reduceComparison);
1269
1270 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001271 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001272 builder.clearAccessChain();
1273 builder.setAccessChainRValue(result);
1274
1275 return false;
1276 }
1277
John Kessenich426394d2015-07-23 10:22:48 -06001278 //
1279 // Create the list of operands.
1280 //
John Kessenich140f3df2015-06-26 16:58:36 -06001281 glslang::TIntermSequence& glslangOperands = node->getSequence();
1282 std::vector<spv::Id> operands;
1283 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1284 builder.clearAccessChain();
1285 glslangOperands[arg]->traverse(this);
1286
1287 // special case l-value operands; there are just a few
1288 bool lvalue = false;
1289 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001290 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001291 case glslang::EOpModf:
1292 if (arg == 1)
1293 lvalue = true;
1294 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001295 case glslang::EOpInterpolateAtSample:
1296 case glslang::EOpInterpolateAtOffset:
1297 if (arg == 0)
1298 lvalue = true;
1299 break;
Rex Xud4782c12015-09-06 16:30:11 +08001300 case glslang::EOpAtomicAdd:
1301 case glslang::EOpAtomicMin:
1302 case glslang::EOpAtomicMax:
1303 case glslang::EOpAtomicAnd:
1304 case glslang::EOpAtomicOr:
1305 case glslang::EOpAtomicXor:
1306 case glslang::EOpAtomicExchange:
1307 case glslang::EOpAtomicCompSwap:
1308 if (arg == 0)
1309 lvalue = true;
1310 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001311 case glslang::EOpAddCarry:
1312 case glslang::EOpSubBorrow:
1313 if (arg == 2)
1314 lvalue = true;
1315 break;
1316 case glslang::EOpUMulExtended:
1317 case glslang::EOpIMulExtended:
1318 if (arg >= 2)
1319 lvalue = true;
1320 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001321 default:
1322 break;
1323 }
1324 if (lvalue)
1325 operands.push_back(builder.accessChainGetLValue());
1326 else
John Kessenich32cfd492016-02-02 12:37:46 -07001327 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001328 }
John Kessenich426394d2015-07-23 10:22:48 -06001329
1330 if (atomic) {
1331 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001332 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001333 } else {
1334 // Pass through to generic operations.
1335 switch (glslangOperands.size()) {
1336 case 0:
1337 result = createNoArgOperation(node->getOp());
1338 break;
1339 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001340 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001341 break;
1342 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001343 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001344 break;
1345 }
John Kessenich140f3df2015-06-26 16:58:36 -06001346 }
1347
1348 if (noReturnValue)
1349 return false;
1350
1351 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001352 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001353 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001354 } else {
1355 builder.clearAccessChain();
1356 builder.setAccessChainRValue(result);
1357 return false;
1358 }
1359}
1360
1361bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1362{
1363 // This path handles both if-then-else and ?:
1364 // The if-then-else has a node type of void, while
1365 // ?: has a non-void node type
1366 spv::Id result = 0;
1367 if (node->getBasicType() != glslang::EbtVoid) {
1368 // don't handle this as just on-the-fly temporaries, because there will be two names
1369 // and better to leave SSA to later passes
1370 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1371 }
1372
1373 // emit the condition before doing anything with selection
1374 node->getCondition()->traverse(this);
1375
1376 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001377 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001378
1379 if (node->getTrueBlock()) {
1380 // emit the "then" statement
1381 node->getTrueBlock()->traverse(this);
1382 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001383 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001384 }
1385
1386 if (node->getFalseBlock()) {
1387 ifBuilder.makeBeginElse();
1388 // emit the "else" statement
1389 node->getFalseBlock()->traverse(this);
1390 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001391 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001392 }
1393
1394 ifBuilder.makeEndIf();
1395
1396 if (result) {
1397 // GLSL only has r-values as the result of a :?, but
1398 // if we have an l-value, that can be more efficient if it will
1399 // become the base of a complex r-value expression, because the
1400 // next layer copies r-values into memory to use the access-chain mechanism
1401 builder.clearAccessChain();
1402 builder.setAccessChainLValue(result);
1403 }
1404
1405 return false;
1406}
1407
1408bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1409{
1410 // emit and get the condition before doing anything with switch
1411 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001412 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001413
1414 // browse the children to sort out code segments
1415 int defaultSegment = -1;
1416 std::vector<TIntermNode*> codeSegments;
1417 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1418 std::vector<int> caseValues;
1419 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1420 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1421 TIntermNode* child = *c;
1422 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001423 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001424 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001425 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001426 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1427 } else
1428 codeSegments.push_back(child);
1429 }
1430
1431 // handle the case where the last code segment is missing, due to no code
1432 // statements between the last case and the end of the switch statement
1433 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1434 (int)codeSegments.size() == defaultSegment)
1435 codeSegments.push_back(nullptr);
1436
1437 // make the switch statement
1438 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001439 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001440
1441 // emit all the code in the segments
1442 breakForLoop.push(false);
1443 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1444 builder.nextSwitchSegment(segmentBlocks, s);
1445 if (codeSegments[s])
1446 codeSegments[s]->traverse(this);
1447 else
1448 builder.addSwitchBreak();
1449 }
1450 breakForLoop.pop();
1451
1452 builder.endSwitch(segmentBlocks);
1453
1454 return false;
1455}
1456
1457void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1458{
1459 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001460 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001461
1462 builder.clearAccessChain();
1463 builder.setAccessChainRValue(constant);
1464}
1465
1466bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1467{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001468 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001469 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001470 // Spec requires back edges to target header blocks, and every header block
1471 // must dominate its merge block. Make a header block first to ensure these
1472 // conditions are met. By definition, it will contain OpLoopMerge, followed
1473 // by a block-ending branch. But we don't want to put any other body/test
1474 // instructions in it, since the body/test may have arbitrary instructions,
1475 // including merges of its own.
1476 builder.setBuildPoint(&blocks.head);
1477 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001478 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001479 spv::Block& test = builder.makeNewBlock();
1480 builder.createBranch(&test);
1481
1482 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001483 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001484 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001485 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001486 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1487
1488 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001489 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001490 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001491 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001492 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001493 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001494
1495 builder.setBuildPoint(&blocks.continue_target);
1496 if (node->getTerminal())
1497 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001498 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001499 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001500 builder.createBranch(&blocks.body);
1501
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001502 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001503 builder.setBuildPoint(&blocks.body);
1504 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001505 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001506 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001507 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001508
1509 builder.setBuildPoint(&blocks.continue_target);
1510 if (node->getTerminal())
1511 node->getTerminal()->traverse(this);
1512 if (node->getTest()) {
1513 node->getTest()->traverse(this);
1514 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001515 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001516 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001517 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001518 // TODO: unless there was a break/return/discard instruction
1519 // somewhere in the body, this is an infinite loop, so we should
1520 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001521 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001522 }
John Kessenich140f3df2015-06-26 16:58:36 -06001523 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001524 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001525 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001526 return false;
1527}
1528
1529bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1530{
1531 if (node->getExpression())
1532 node->getExpression()->traverse(this);
1533
1534 switch (node->getFlowOp()) {
1535 case glslang::EOpKill:
1536 builder.makeDiscard();
1537 break;
1538 case glslang::EOpBreak:
1539 if (breakForLoop.top())
1540 builder.createLoopExit();
1541 else
1542 builder.addSwitchBreak();
1543 break;
1544 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001545 builder.createLoopContinue();
1546 break;
1547 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001548 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001549 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001550 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001551 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001552
1553 builder.clearAccessChain();
1554 break;
1555
1556 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001557 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001558 break;
1559 }
1560
1561 return false;
1562}
1563
1564spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1565{
1566 // First, steer off constants, which are not SPIR-V variables, but
1567 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001568 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001569 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001570 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001571 }
1572
1573 // Now, handle actual variables
1574 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1575 spv::Id spvType = convertGlslangToSpvType(node->getType());
1576
1577 const char* name = node->getName().c_str();
1578 if (glslang::IsAnonymous(name))
1579 name = "";
1580
1581 return builder.createVariable(storageClass, spvType, name);
1582}
1583
1584// Return type Id of the sampled type.
1585spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1586{
1587 switch (sampler.type) {
1588 case glslang::EbtFloat: return builder.makeFloatType(32);
1589 case glslang::EbtInt: return builder.makeIntType(32);
1590 case glslang::EbtUint: return builder.makeUintType(32);
1591 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001592 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001593 return builder.makeFloatType(32);
1594 }
1595}
1596
John Kessenich3ac051e2015-12-20 11:29:16 -07001597// Convert from a glslang type to an SPV type, by calling into a
1598// recursive version of this function. This establishes the inherited
1599// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001600spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1601{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001602 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001603}
1604
1605// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001606// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001607spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001608{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001609 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001610
1611 switch (type.getBasicType()) {
1612 case glslang::EbtVoid:
1613 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001614 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001615 break;
1616 case glslang::EbtFloat:
1617 spvType = builder.makeFloatType(32);
1618 break;
1619 case glslang::EbtDouble:
1620 spvType = builder.makeFloatType(64);
1621 break;
1622 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001623 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1624 // a 32-bit int where non-0 means true.
1625 if (explicitLayout != glslang::ElpNone)
1626 spvType = builder.makeUintType(32);
1627 else
1628 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001629 break;
1630 case glslang::EbtInt:
1631 spvType = builder.makeIntType(32);
1632 break;
1633 case glslang::EbtUint:
1634 spvType = builder.makeUintType(32);
1635 break;
John Kessenich426394d2015-07-23 10:22:48 -06001636 case glslang::EbtAtomicUint:
1637 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1638 spvType = builder.makeUintType(32);
1639 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001640 case glslang::EbtSampler:
1641 {
1642 const glslang::TSampler& sampler = type.getSampler();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001643 // an image is present, make its type
1644 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1645 sampler.image ? 2 : 1, TranslateImageFormat(type));
John Kessenich55e7d112015-11-15 21:33:39 -07001646 if (! sampler.image) {
John Kesseniche0b6cad2015-12-24 10:30:13 -07001647 spvType = builder.makeSampledImageType(spvType);
John Kessenich55e7d112015-11-15 21:33:39 -07001648 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001649 }
John Kessenich140f3df2015-06-26 16:58:36 -06001650 break;
1651 case glslang::EbtStruct:
1652 case glslang::EbtBlock:
1653 {
1654 // If we've seen this struct type, return it
1655 const glslang::TTypeList* glslangStruct = type.getStruct();
1656 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001657
1658 // Try to share structs for different layouts, but not yet for other
1659 // kinds of qualification (primarily not yet including interpolant qualification).
1660 if (! HasNonLayoutQualifiers(qualifier))
1661 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1662 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001663 break;
1664
1665 // else, we haven't seen it...
1666
1667 // Create a vector of struct types for SPIR-V to consume
1668 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1669 if (type.getBasicType() == glslang::EbtBlock)
1670 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001671 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001672 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1673 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1674 if (glslangType.hiddenMember()) {
1675 ++memberDelta;
1676 if (type.getBasicType() == glslang::EbtBlock)
1677 memberRemapper[glslangStruct][i] = -1;
1678 } else {
1679 if (type.getBasicType() == glslang::EbtBlock)
1680 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001681 // modify just this child's view of the qualifier
1682 glslang::TQualifier subQualifier = glslangType.getQualifier();
1683 InheritQualifiers(subQualifier, qualifier);
John Kessenich7b9fa252016-01-21 18:56:57 -07001684 if (qualifier.hasLocation()) {
1685 subQualifier.layoutLocation += locationOffset;
1686 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1687 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001688 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001689 }
1690 }
1691
1692 // Make the SPIR-V type
1693 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001694 if (! HasNonLayoutQualifiers(qualifier))
1695 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001696
1697 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001698 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001699 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001700 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1701 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1702 int member = i;
1703 if (type.getBasicType() == glslang::EbtBlock)
1704 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001705
John Kesseniche0b6cad2015-12-24 10:30:13 -07001706 // modify just this child's view of the qualifier
1707 glslang::TQualifier subQualifier = glslangType.getQualifier();
1708 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001709
John Kessenich140f3df2015-06-26 16:58:36 -06001710 // using -1 above to indicate a hidden member
1711 if (member >= 0) {
1712 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001713 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001714 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001715 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1716 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich7b9fa252016-01-21 18:56:57 -07001717 if (qualifier.hasLocation()) {
1718 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, qualifier.layoutLocation + locationOffset);
1719 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1720 }
John Kessenich140f3df2015-06-26 16:58:36 -06001721 if (glslangType.getQualifier().hasComponent())
1722 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1723 if (glslangType.getQualifier().hasXfbOffset())
1724 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001725 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001726 // figure out what to do with offset, which is accumulating
1727 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001728 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001729 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001730 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001731 offset = nextOffset;
1732 }
John Kessenich140f3df2015-06-26 16:58:36 -06001733
John Kessenichf85e8062015-12-19 13:57:10 -07001734 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001735 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001736
John Kessenich140f3df2015-06-26 16:58:36 -06001737 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001738 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1739 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001740 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001741 }
1742 }
1743
1744 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001745 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001746 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenich92187592016-02-01 13:45:25 -07001747 if (type.getQualifier().hasStream()) {
1748 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001749 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001750 }
John Kessenich140f3df2015-06-26 16:58:36 -06001751 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001752 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001753 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001754 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001755 if (type.getQualifier().hasXfbBuffer())
1756 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1757 }
1758 }
1759 break;
1760 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001761 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001762 break;
1763 }
1764
1765 if (type.isMatrix())
1766 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1767 else {
1768 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1769 if (type.getVectorSize() > 1)
1770 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1771 }
1772
1773 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001774 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1775
John Kessenichc9a80832015-09-12 12:17:44 -06001776 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001777 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001778 // We need to decorate array strides for types needing explicit layout, except blocks.
1779 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001780 // Use a dummy glslang type for querying internal strides of
1781 // arrays of arrays, but using just a one-dimensional array.
1782 glslang::TType simpleArrayType(type, 0); // deference type of the array
1783 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1784 simpleArrayType.getArraySizes().dereference();
1785
1786 // Will compute the higher-order strides here, rather than making a whole
1787 // pile of types and doing repetitive recursion on their contents.
1788 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1789 }
John Kessenichf8842e52016-01-04 19:22:56 -07001790
1791 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001792 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1793 int size = type.getArraySizes()->getDimSize(dim);
1794 assert(size > 0);
1795 spvType = builder.makeArrayType(spvType, size, stride);
1796 if (stride > 0)
1797 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
1798 stride *= size;
1799 }
1800 } else {
1801 // single-dimensional array, and don't yet have stride
1802
John Kessenichf8842e52016-01-04 19:22:56 -07001803 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001804 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1805 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001806 }
John Kessenich31ed4832015-09-09 17:51:38 -06001807
John Kessenichc9a80832015-09-12 12:17:44 -06001808 // Do the outer dimension, which might not be known for a runtime-sized array
1809 if (type.isRuntimeSizedArray()) {
1810 spvType = builder.makeRuntimeArray(spvType);
1811 } else {
1812 assert(type.getOuterArraySize() > 0);
John Kessenichc9e0a422015-12-29 21:27:24 -07001813 spvType = builder.makeArrayType(spvType, type.getOuterArraySize(), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001814 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001815 if (stride > 0)
1816 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001817 }
1818
1819 return spvType;
1820}
1821
John Kessenich103bef92016-02-08 21:38:15 -07001822// Wrap the builder's accessChainLoad to:
1823// - localize handling of RelaxedPrecision
1824// - use the SPIR-V inferred type instead of another conversion of the glslang type
1825// (avoids unnecessary work and possible type punning for structures)
1826// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001827spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1828{
John Kessenich103bef92016-02-08 21:38:15 -07001829 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1830 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1831
1832 // Need to convert to abstract types when necessary
1833 if (builder.isScalarType(nominalTypeId) && type.getBasicType() == glslang::EbtBool && nominalTypeId != builder.makeBoolType())
1834 loadedId = builder.createBinOp(spv::OpINotEqual, builder.makeBoolType(), loadedId, builder.makeUintConstant(0));
1835
1836 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07001837}
1838
John Kessenichf85e8062015-12-19 13:57:10 -07001839// Decide whether or not this type should be
1840// decorated with offsets and strides, and if so
1841// whether std140 or std430 rules should be applied.
1842glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001843{
John Kessenichf85e8062015-12-19 13:57:10 -07001844 // has to be a block
1845 if (type.getBasicType() != glslang::EbtBlock)
1846 return glslang::ElpNone;
1847
1848 // has to be a uniform or buffer block
1849 if (type.getQualifier().storage != glslang::EvqUniform &&
1850 type.getQualifier().storage != glslang::EvqBuffer)
1851 return glslang::ElpNone;
1852
1853 // return the layout to use
1854 switch (type.getQualifier().layoutPacking) {
1855 case glslang::ElpStd140:
1856 case glslang::ElpStd430:
1857 return type.getQualifier().layoutPacking;
1858 default:
1859 return glslang::ElpNone;
1860 }
John Kessenich31ed4832015-09-09 17:51:38 -06001861}
1862
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001863// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001864int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001865{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001866 int size;
John Kessenich49987892015-12-29 17:11:44 -07001867 int stride;
1868 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001869
1870 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001871}
1872
John Kessenich49987892015-12-29 17:11:44 -07001873// 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 -07001874// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001875int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001876{
John Kessenich49987892015-12-29 17:11:44 -07001877 glslang::TType elementType;
1878 elementType.shallowCopy(matrixType);
1879 elementType.clearArraySizes();
1880
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001881 int size;
John Kessenich49987892015-12-29 17:11:44 -07001882 int stride;
1883 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
1884
1885 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001886}
1887
John Kessenich5e4b1242015-08-06 22:53:06 -06001888// Given a member type of a struct, realign the current offset for it, and compute
1889// the next (not yet aligned) offset for the next member, which will get aligned
1890// on the next call.
1891// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1892// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1893// -1 means a non-forced member offset (no decoration needed).
John Kessenichf85e8062015-12-19 13:57:10 -07001894void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07001895 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06001896{
1897 // this will get a positive value when deemed necessary
1898 nextOffset = -1;
1899
John Kessenich5e4b1242015-08-06 22:53:06 -06001900 // override anything in currentOffset with user-set offset
1901 if (memberType.getQualifier().hasOffset())
1902 currentOffset = memberType.getQualifier().layoutOffset;
1903
1904 // It could be that current linker usage in glslang updated all the layoutOffset,
1905 // in which case the following code does not matter. But, that's not quite right
1906 // once cross-compilation unit GLSL validation is done, as the original user
1907 // settings are needed in layoutOffset, and then the following will come into play.
1908
John Kessenichf85e8062015-12-19 13:57:10 -07001909 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001910 if (! memberType.getQualifier().hasOffset())
1911 currentOffset = -1;
1912
1913 return;
1914 }
1915
John Kessenichf85e8062015-12-19 13:57:10 -07001916 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06001917 if (currentOffset < 0)
1918 currentOffset = 0;
1919
1920 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1921 // but possibly not yet correctly aligned.
1922
1923 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07001924 int dummyStride;
1925 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06001926 glslang::RoundToPow2(currentOffset, memberAlignment);
1927 nextOffset = currentOffset + memberSize;
1928}
1929
John Kessenich140f3df2015-06-26 16:58:36 -06001930bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1931{
1932 return node->getName() == "main(";
1933}
1934
1935// Make all the functions, skeletally, without actually visiting their bodies.
1936void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1937{
1938 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1939 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1940 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1941 continue;
1942
1943 // We're on a user function. Set up the basic interface for the function now,
1944 // so that it's available to call.
1945 // Translating the body will happen later.
1946 //
1947 // Typically (except for a "const in" parameter), an address will be passed to the
1948 // function. What it is an address of varies:
1949 //
1950 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1951 // so that write needs to be to a copy, hence the address of a copy works.
1952 //
1953 // - "const in" parameters can just be the r-value, as no writes need occur.
1954 //
1955 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1956 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1957
1958 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07001959 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06001960 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1961
1962 for (int p = 0; p < (int)parameters.size(); ++p) {
1963 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1964 spv::Id typeId = convertGlslangToSpvType(paramType);
1965 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1966 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1967 else
1968 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07001969 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06001970 paramTypes.push_back(typeId);
1971 }
1972
1973 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07001974 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
1975 convertGlslangToSpvType(glslFunction->getType()),
1976 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06001977
1978 // Track function to emit/call later
1979 functionMap[glslFunction->getName().c_str()] = function;
1980
1981 // Set the parameter id's
1982 for (int p = 0; p < (int)parameters.size(); ++p) {
1983 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1984 // give a name too
1985 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1986 }
1987 }
1988}
1989
1990// Process all the initializers, while skipping the functions and link objects
1991void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1992{
1993 builder.setBuildPoint(shaderEntry->getLastBlock());
1994 for (int i = 0; i < (int)initializers.size(); ++i) {
1995 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1996 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1997
1998 // We're on a top-level node that's not a function. Treat as an initializer, whose
1999 // code goes into the beginning of main.
2000 initializer->traverse(this);
2001 }
2002 }
2003}
2004
2005// Process all the functions, while skipping initializers.
2006void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2007{
2008 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2009 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2010 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2011 node->traverse(this);
2012 }
2013}
2014
2015void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2016{
2017 // SPIR-V functions should already be in the functionMap from the prepass
2018 // that called makeFunctions().
2019 spv::Function* function = functionMap[node->getName().c_str()];
2020 spv::Block* functionBlock = function->getEntryBlock();
2021 builder.setBuildPoint(functionBlock);
2022}
2023
Rex Xu04db3f52015-09-16 11:44:02 +08002024void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002025{
Rex Xufc618912015-09-09 16:42:49 +08002026 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002027
2028 glslang::TSampler sampler = {};
2029 bool cubeCompare = false;
2030 if (node.isTexture()) {
2031 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2032 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2033 }
2034
John Kessenich140f3df2015-06-26 16:58:36 -06002035 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2036 builder.clearAccessChain();
2037 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002038
2039 // Special case l-value operands
2040 bool lvalue = false;
2041 switch (node.getOp()) {
2042 case glslang::EOpImageAtomicAdd:
2043 case glslang::EOpImageAtomicMin:
2044 case glslang::EOpImageAtomicMax:
2045 case glslang::EOpImageAtomicAnd:
2046 case glslang::EOpImageAtomicOr:
2047 case glslang::EOpImageAtomicXor:
2048 case glslang::EOpImageAtomicExchange:
2049 case glslang::EOpImageAtomicCompSwap:
2050 if (i == 0)
2051 lvalue = true;
2052 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002053 case glslang::EOpSparseTexture:
2054 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2055 lvalue = true;
2056 break;
2057 case glslang::EOpSparseTextureClamp:
2058 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2059 lvalue = true;
2060 break;
2061 case glslang::EOpSparseTextureLod:
2062 case glslang::EOpSparseTextureOffset:
2063 if (i == 3)
2064 lvalue = true;
2065 break;
2066 case glslang::EOpSparseTextureFetch:
2067 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2068 lvalue = true;
2069 break;
2070 case glslang::EOpSparseTextureFetchOffset:
2071 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2072 lvalue = true;
2073 break;
2074 case glslang::EOpSparseTextureLodOffset:
2075 case glslang::EOpSparseTextureGrad:
2076 case glslang::EOpSparseTextureOffsetClamp:
2077 if (i == 4)
2078 lvalue = true;
2079 break;
2080 case glslang::EOpSparseTextureGradOffset:
2081 case glslang::EOpSparseTextureGradClamp:
2082 if (i == 5)
2083 lvalue = true;
2084 break;
2085 case glslang::EOpSparseTextureGradOffsetClamp:
2086 if (i == 6)
2087 lvalue = true;
2088 break;
2089 case glslang::EOpSparseTextureGather:
2090 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2091 lvalue = true;
2092 break;
2093 case glslang::EOpSparseTextureGatherOffset:
2094 case glslang::EOpSparseTextureGatherOffsets:
2095 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2096 lvalue = true;
2097 break;
Rex Xufc618912015-09-09 16:42:49 +08002098 default:
2099 break;
2100 }
2101
Rex Xu6b86d492015-09-16 17:48:22 +08002102 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002103 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002104 else
John Kessenich32cfd492016-02-02 12:37:46 -07002105 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002106 }
2107}
2108
John Kessenichfc51d282015-08-19 13:34:18 -06002109void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002110{
John Kessenichfc51d282015-08-19 13:34:18 -06002111 builder.clearAccessChain();
2112 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002113 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002114}
John Kessenich140f3df2015-06-26 16:58:36 -06002115
John Kessenichfc51d282015-08-19 13:34:18 -06002116spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2117{
Rex Xufc618912015-09-09 16:42:49 +08002118 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002119 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002120 }
2121
John Kessenichfc51d282015-08-19 13:34:18 -06002122 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002123 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2124 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2125 std::vector<spv::Id> arguments;
2126 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002127 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002128 else
2129 translateArguments(*node->getAsUnaryNode(), arguments);
2130 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2131
2132 spv::Builder::TextureParameters params = { };
2133 params.sampler = arguments[0];
2134
Rex Xu04db3f52015-09-16 11:44:02 +08002135 glslang::TCrackedTextureOp cracked;
2136 node->crackTexture(sampler, cracked);
2137
John Kessenichfc51d282015-08-19 13:34:18 -06002138 // Check for queries
2139 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002140 // a sampled image needs to have the image extracted first
2141 if (builder.isSampledImage(params.sampler))
2142 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002143 switch (node->getOp()) {
2144 case glslang::EOpImageQuerySize:
2145 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002146 if (arguments.size() > 1) {
2147 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002148 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002149 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002150 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002151 case glslang::EOpImageQuerySamples:
2152 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002153 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002154 case glslang::EOpTextureQueryLod:
2155 params.coords = arguments[1];
2156 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2157 case glslang::EOpTextureQueryLevels:
2158 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002159 case glslang::EOpSparseTexelsResident:
2160 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002161 default:
2162 assert(0);
2163 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002164 }
John Kessenich140f3df2015-06-26 16:58:36 -06002165 }
2166
Rex Xufc618912015-09-09 16:42:49 +08002167 // Check for image functions other than queries
2168 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002169 std::vector<spv::Id> operands;
2170 auto opIt = arguments.begin();
2171 operands.push_back(*(opIt++));
2172 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002173 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002174 if (sampler.ms) {
2175 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002176 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002177 }
John Kessenich56bab042015-09-16 10:54:31 -06002178 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002179 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2180 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002181 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002182 if (sampler.ms) {
2183 operands.push_back(*(opIt + 1));
2184 operands.push_back(spv::ImageOperandsSampleMask);
2185 operands.push_back(*opIt);
2186 } else
2187 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002188 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002189 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2190 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002191 return spv::NoResult;
Rex Xu48edadf2015-12-31 16:11:41 +08002192 } else if (node->isSparseImage()) {
2193 spv::MissingFunctionality("sparse image functions");
2194 return spv::NoResult;
John Kessenichcd261442016-01-22 09:54:12 -07002195 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002196 // Process image atomic operations
2197
2198 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2199 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002200 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002201
Rex Xufc618912015-09-09 16:42:49 +08002202 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002203 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002204
2205 std::vector<spv::Id> operands;
2206 operands.push_back(pointer);
2207 for (; opIt != arguments.end(); ++opIt)
2208 operands.push_back(*opIt);
2209
Rex Xu04db3f52015-09-16 11:44:02 +08002210 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002211 }
2212 }
2213
2214 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002215 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002216 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2217
John Kessenichfc51d282015-08-19 13:34:18 -06002218 // check for bias argument
2219 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002220 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002221 int nonBiasArgCount = 2;
2222 if (cracked.offset)
2223 ++nonBiasArgCount;
2224 if (cracked.grad)
2225 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002226 if (cracked.lodClamp)
2227 ++nonBiasArgCount;
2228 if (sparse)
2229 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002230
2231 if ((int)arguments.size() > nonBiasArgCount)
2232 bias = true;
2233 }
2234
John Kessenichfc51d282015-08-19 13:34:18 -06002235 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002236
John Kessenichfc51d282015-08-19 13:34:18 -06002237 params.coords = arguments[1];
2238 int extraArgs = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07002239
2240 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002241 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002242 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002243 ++extraArgs;
2244 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002245 params.Dref = arguments[2];
2246 ++extraArgs;
2247 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002248 std::vector<spv::Id> indexes;
2249 int comp;
2250 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002251 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002252 else
2253 comp = builder.getNumComponents(params.coords) - 1;
2254 indexes.push_back(comp);
2255 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2256 }
2257 if (cracked.lod) {
2258 params.lod = arguments[2];
2259 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08002260 } else if (sampler.ms) {
2261 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002262 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002263 }
2264 if (cracked.grad) {
2265 params.gradX = arguments[2 + extraArgs];
2266 params.gradY = arguments[3 + extraArgs];
2267 extraArgs += 2;
2268 }
John Kessenich55e7d112015-11-15 21:33:39 -07002269 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002270 params.offset = arguments[2 + extraArgs];
2271 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002272 } else if (cracked.offsets) {
2273 params.offsets = arguments[2 + extraArgs];
2274 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002275 }
Rex Xu48edadf2015-12-31 16:11:41 +08002276 if (cracked.lodClamp) {
2277 params.lodClamp = arguments[2 + extraArgs];
2278 ++extraArgs;
2279 }
2280 if (sparse) {
2281 params.texelOut = arguments[2 + extraArgs];
2282 ++extraArgs;
2283 }
John Kessenichfc51d282015-08-19 13:34:18 -06002284 if (bias) {
2285 params.bias = arguments[2 + extraArgs];
2286 ++extraArgs;
2287 }
John Kessenich55e7d112015-11-15 21:33:39 -07002288 if (cracked.gather && ! sampler.shadow) {
2289 // default component is 0, if missing, otherwise an argument
2290 if (2 + extraArgs < (int)arguments.size()) {
2291 params.comp = arguments[2 + extraArgs];
2292 ++extraArgs;
2293 } else {
2294 params.comp = builder.makeIntConstant(0);
2295 }
2296 }
John Kessenichfc51d282015-08-19 13:34:18 -06002297
Rex Xu48edadf2015-12-31 16:11:41 +08002298 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002299}
2300
2301spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2302{
2303 // Grab the function's pointer from the previously created function
2304 spv::Function* function = functionMap[node->getName().c_str()];
2305 if (! function)
2306 return 0;
2307
2308 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2309 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2310
2311 // See comments in makeFunctions() for details about the semantics for parameter passing.
2312 //
2313 // These imply we need a four step process:
2314 // 1. Evaluate the arguments
2315 // 2. Allocate and make copies of in, out, and inout arguments
2316 // 3. Make the call
2317 // 4. Copy back the results
2318
2319 // 1. Evaluate the arguments
2320 std::vector<spv::Builder::AccessChain> lValues;
2321 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002322 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002323 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2324 // build l-value
2325 builder.clearAccessChain();
2326 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002327 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002328 // keep outputs as l-values, evaluate input-only as r-values
2329 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2330 // save l-value
2331 lValues.push_back(builder.getAccessChain());
2332 } else {
2333 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002334 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002335 }
2336 }
2337
2338 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2339 // copy the original into that space.
2340 //
2341 // Also, build up the list of actual arguments to pass in for the call
2342 int lValueCount = 0;
2343 int rValueCount = 0;
2344 std::vector<spv::Id> spvArgs;
2345 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2346 spv::Id arg;
2347 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2348 // need space to hold the copy
2349 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2350 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2351 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2352 // need to copy the input into output space
2353 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002354 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002355 builder.createStore(copy, arg);
2356 }
2357 ++lValueCount;
2358 } else {
2359 arg = rValues[rValueCount];
2360 ++rValueCount;
2361 }
2362 spvArgs.push_back(arg);
2363 }
2364
2365 // 3. Make the call.
2366 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002367 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002368
2369 // 4. Copy back out an "out" arguments.
2370 lValueCount = 0;
2371 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2372 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2373 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2374 spv::Id copy = builder.createLoad(spvArgs[a]);
2375 builder.setAccessChain(lValues[lValueCount]);
2376 builder.accessChainStore(copy);
2377 }
2378 ++lValueCount;
2379 }
2380 }
2381
2382 return result;
2383}
2384
2385// Translate AST operation to SPV operation, already having SPV-based operands/types.
2386spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2387 spv::Id typeId, spv::Id left, spv::Id right,
2388 glslang::TBasicType typeProxy, bool reduceComparison)
2389{
2390 bool isUnsigned = typeProxy == glslang::EbtUint;
2391 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2392
2393 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002394 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002395 bool comparison = false;
2396
2397 switch (op) {
2398 case glslang::EOpAdd:
2399 case glslang::EOpAddAssign:
2400 if (isFloat)
2401 binOp = spv::OpFAdd;
2402 else
2403 binOp = spv::OpIAdd;
2404 break;
2405 case glslang::EOpSub:
2406 case glslang::EOpSubAssign:
2407 if (isFloat)
2408 binOp = spv::OpFSub;
2409 else
2410 binOp = spv::OpISub;
2411 break;
2412 case glslang::EOpMul:
2413 case glslang::EOpMulAssign:
2414 if (isFloat)
2415 binOp = spv::OpFMul;
2416 else
2417 binOp = spv::OpIMul;
2418 break;
2419 case glslang::EOpVectorTimesScalar:
2420 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002421 if (isFloat) {
2422 if (builder.isVector(right))
2423 std::swap(left, right);
2424 assert(builder.isScalar(right));
2425 needMatchingVectors = false;
2426 binOp = spv::OpVectorTimesScalar;
2427 } else
2428 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002429 break;
2430 case glslang::EOpVectorTimesMatrix:
2431 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002432 binOp = spv::OpVectorTimesMatrix;
2433 break;
2434 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002435 binOp = spv::OpMatrixTimesVector;
2436 break;
2437 case glslang::EOpMatrixTimesScalar:
2438 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002439 binOp = spv::OpMatrixTimesScalar;
2440 break;
2441 case glslang::EOpMatrixTimesMatrix:
2442 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002443 binOp = spv::OpMatrixTimesMatrix;
2444 break;
2445 case glslang::EOpOuterProduct:
2446 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002447 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002448 break;
2449
2450 case glslang::EOpDiv:
2451 case glslang::EOpDivAssign:
2452 if (isFloat)
2453 binOp = spv::OpFDiv;
2454 else if (isUnsigned)
2455 binOp = spv::OpUDiv;
2456 else
2457 binOp = spv::OpSDiv;
2458 break;
2459 case glslang::EOpMod:
2460 case glslang::EOpModAssign:
2461 if (isFloat)
2462 binOp = spv::OpFMod;
2463 else if (isUnsigned)
2464 binOp = spv::OpUMod;
2465 else
2466 binOp = spv::OpSMod;
2467 break;
2468 case glslang::EOpRightShift:
2469 case glslang::EOpRightShiftAssign:
2470 if (isUnsigned)
2471 binOp = spv::OpShiftRightLogical;
2472 else
2473 binOp = spv::OpShiftRightArithmetic;
2474 break;
2475 case glslang::EOpLeftShift:
2476 case glslang::EOpLeftShiftAssign:
2477 binOp = spv::OpShiftLeftLogical;
2478 break;
2479 case glslang::EOpAnd:
2480 case glslang::EOpAndAssign:
2481 binOp = spv::OpBitwiseAnd;
2482 break;
2483 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002484 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002485 binOp = spv::OpLogicalAnd;
2486 break;
2487 case glslang::EOpInclusiveOr:
2488 case glslang::EOpInclusiveOrAssign:
2489 binOp = spv::OpBitwiseOr;
2490 break;
2491 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002492 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002493 binOp = spv::OpLogicalOr;
2494 break;
2495 case glslang::EOpExclusiveOr:
2496 case glslang::EOpExclusiveOrAssign:
2497 binOp = spv::OpBitwiseXor;
2498 break;
2499 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002500 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002501 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002502 break;
2503
2504 case glslang::EOpLessThan:
2505 case glslang::EOpGreaterThan:
2506 case glslang::EOpLessThanEqual:
2507 case glslang::EOpGreaterThanEqual:
2508 case glslang::EOpEqual:
2509 case glslang::EOpNotEqual:
2510 case glslang::EOpVectorEqual:
2511 case glslang::EOpVectorNotEqual:
2512 comparison = true;
2513 break;
2514 default:
2515 break;
2516 }
2517
John Kessenich7c1aa102015-10-15 13:29:11 -06002518 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002519 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002520 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002521 if (builder.isMatrix(left) || builder.isMatrix(right))
2522 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002523
2524 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002525 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002526 builder.promoteScalar(precision, left, right);
2527
John Kessenich32cfd492016-02-02 12:37:46 -07002528 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002529 }
2530
2531 if (! comparison)
2532 return 0;
2533
John Kessenich7c1aa102015-10-15 13:29:11 -06002534 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002535
2536 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2537 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2538
John Kessenich22118352015-12-21 20:54:09 -07002539 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002540 }
2541
2542 switch (op) {
2543 case glslang::EOpLessThan:
2544 if (isFloat)
2545 binOp = spv::OpFOrdLessThan;
2546 else if (isUnsigned)
2547 binOp = spv::OpULessThan;
2548 else
2549 binOp = spv::OpSLessThan;
2550 break;
2551 case glslang::EOpGreaterThan:
2552 if (isFloat)
2553 binOp = spv::OpFOrdGreaterThan;
2554 else if (isUnsigned)
2555 binOp = spv::OpUGreaterThan;
2556 else
2557 binOp = spv::OpSGreaterThan;
2558 break;
2559 case glslang::EOpLessThanEqual:
2560 if (isFloat)
2561 binOp = spv::OpFOrdLessThanEqual;
2562 else if (isUnsigned)
2563 binOp = spv::OpULessThanEqual;
2564 else
2565 binOp = spv::OpSLessThanEqual;
2566 break;
2567 case glslang::EOpGreaterThanEqual:
2568 if (isFloat)
2569 binOp = spv::OpFOrdGreaterThanEqual;
2570 else if (isUnsigned)
2571 binOp = spv::OpUGreaterThanEqual;
2572 else
2573 binOp = spv::OpSGreaterThanEqual;
2574 break;
2575 case glslang::EOpEqual:
2576 case glslang::EOpVectorEqual:
2577 if (isFloat)
2578 binOp = spv::OpFOrdEqual;
2579 else
2580 binOp = spv::OpIEqual;
2581 break;
2582 case glslang::EOpNotEqual:
2583 case glslang::EOpVectorNotEqual:
2584 if (isFloat)
2585 binOp = spv::OpFOrdNotEqual;
2586 else
2587 binOp = spv::OpINotEqual;
2588 break;
2589 default:
2590 break;
2591 }
2592
John Kessenich32cfd492016-02-02 12:37:46 -07002593 if (binOp != spv::OpNop)
2594 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002595
2596 return 0;
2597}
2598
John Kessenich04bb8a02015-12-12 12:28:14 -07002599//
2600// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2601// These can be any of:
2602//
2603// matrix * scalar
2604// scalar * matrix
2605// matrix * matrix linear algebraic
2606// matrix * vector
2607// vector * matrix
2608// matrix * matrix componentwise
2609// matrix op matrix op in {+, -, /}
2610// matrix op scalar op in {+, -, /}
2611// scalar op matrix op in {+, -, /}
2612//
2613spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2614{
2615 bool firstClass = true;
2616
2617 // First, handle first-class matrix operations (* and matrix/scalar)
2618 switch (op) {
2619 case spv::OpFDiv:
2620 if (builder.isMatrix(left) && builder.isScalar(right)) {
2621 // turn matrix / scalar into a multiply...
2622 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2623 op = spv::OpMatrixTimesScalar;
2624 } else
2625 firstClass = false;
2626 break;
2627 case spv::OpMatrixTimesScalar:
2628 if (builder.isMatrix(right))
2629 std::swap(left, right);
2630 assert(builder.isScalar(right));
2631 break;
2632 case spv::OpVectorTimesMatrix:
2633 assert(builder.isVector(left));
2634 assert(builder.isMatrix(right));
2635 break;
2636 case spv::OpMatrixTimesVector:
2637 assert(builder.isMatrix(left));
2638 assert(builder.isVector(right));
2639 break;
2640 case spv::OpMatrixTimesMatrix:
2641 assert(builder.isMatrix(left));
2642 assert(builder.isMatrix(right));
2643 break;
2644 default:
2645 firstClass = false;
2646 break;
2647 }
2648
John Kessenich32cfd492016-02-02 12:37:46 -07002649 if (firstClass)
2650 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002651
2652 // Handle component-wise +, -, *, and / for all combinations of type.
2653 // The result type of all of them is the same type as the (a) matrix operand.
2654 // The algorithm is to:
2655 // - break the matrix(es) into vectors
2656 // - smear any scalar to a vector
2657 // - do vector operations
2658 // - make a matrix out the vector results
2659 switch (op) {
2660 case spv::OpFAdd:
2661 case spv::OpFSub:
2662 case spv::OpFDiv:
2663 case spv::OpFMul:
2664 {
2665 // one time set up...
2666 bool leftMat = builder.isMatrix(left);
2667 bool rightMat = builder.isMatrix(right);
2668 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2669 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2670 spv::Id scalarType = builder.getScalarTypeId(typeId);
2671 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2672 std::vector<spv::Id> results;
2673 spv::Id smearVec = spv::NoResult;
2674 if (builder.isScalar(left))
2675 smearVec = builder.smearScalar(precision, left, vecType);
2676 else if (builder.isScalar(right))
2677 smearVec = builder.smearScalar(precision, right, vecType);
2678
2679 // do each vector op
2680 for (unsigned int c = 0; c < numCols; ++c) {
2681 std::vector<unsigned int> indexes;
2682 indexes.push_back(c);
2683 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2684 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2685 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2686 builder.setPrecision(results.back(), precision);
2687 }
2688
2689 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002690 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002691 }
2692 default:
2693 assert(0);
2694 return spv::NoResult;
2695 }
2696}
2697
Rex Xu04db3f52015-09-16 11:44:02 +08002698spv::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 -06002699{
2700 spv::Op unaryOp = spv::OpNop;
2701 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002702 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002703 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002704
2705 switch (op) {
2706 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002707 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002708 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002709 if (builder.isMatrixType(typeId))
2710 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2711 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002712 unaryOp = spv::OpSNegate;
2713 break;
2714
2715 case glslang::EOpLogicalNot:
2716 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002717 unaryOp = spv::OpLogicalNot;
2718 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002719 case glslang::EOpBitwiseNot:
2720 unaryOp = spv::OpNot;
2721 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002722
John Kessenich140f3df2015-06-26 16:58:36 -06002723 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002724 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002725 break;
2726 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002727 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002728 break;
2729 case glslang::EOpTranspose:
2730 unaryOp = spv::OpTranspose;
2731 break;
2732
2733 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002734 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002735 break;
2736 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002737 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002738 break;
2739 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002740 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002741 break;
2742 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002743 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002744 break;
2745 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002746 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002747 break;
2748 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002749 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002750 break;
2751 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002752 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002753 break;
2754 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002755 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002756 break;
2757
2758 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002759 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002760 break;
2761 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002762 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002763 break;
2764 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002765 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002766 break;
2767 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002768 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002769 break;
2770 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002771 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002772 break;
2773 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002774 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002775 break;
2776
2777 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002778 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002779 break;
2780 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002781 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002782 break;
2783
2784 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002785 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002786 break;
2787 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002788 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002789 break;
2790 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002791 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002792 break;
2793 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002794 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002795 break;
2796 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002797 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002798 break;
2799 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002800 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002801 break;
2802
2803 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002804 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002805 break;
2806 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002807 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002808 break;
2809 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002810 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002811 break;
2812 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002813 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002814 break;
2815 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002816 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002817 break;
2818 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002819 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002820 break;
2821
2822 case glslang::EOpIsNan:
2823 unaryOp = spv::OpIsNan;
2824 break;
2825 case glslang::EOpIsInf:
2826 unaryOp = spv::OpIsInf;
2827 break;
2828
Rex Xucbc426e2015-12-15 16:03:10 +08002829 case glslang::EOpFloatBitsToInt:
2830 case glslang::EOpFloatBitsToUint:
2831 case glslang::EOpIntBitsToFloat:
2832 case glslang::EOpUintBitsToFloat:
2833 unaryOp = spv::OpBitcast;
2834 break;
2835
John Kessenich140f3df2015-06-26 16:58:36 -06002836 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002837 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002838 break;
2839 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002840 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002841 break;
2842 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002843 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002844 break;
2845 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002846 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002847 break;
2848 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002849 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002850 break;
2851 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002852 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002853 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002854 case glslang::EOpPackSnorm4x8:
2855 libCall = spv::GLSLstd450PackSnorm4x8;
2856 break;
2857 case glslang::EOpUnpackSnorm4x8:
2858 libCall = spv::GLSLstd450UnpackSnorm4x8;
2859 break;
2860 case glslang::EOpPackUnorm4x8:
2861 libCall = spv::GLSLstd450PackUnorm4x8;
2862 break;
2863 case glslang::EOpUnpackUnorm4x8:
2864 libCall = spv::GLSLstd450UnpackUnorm4x8;
2865 break;
2866 case glslang::EOpPackDouble2x32:
2867 libCall = spv::GLSLstd450PackDouble2x32;
2868 break;
2869 case glslang::EOpUnpackDouble2x32:
2870 libCall = spv::GLSLstd450UnpackDouble2x32;
2871 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002872
2873 case glslang::EOpDPdx:
2874 unaryOp = spv::OpDPdx;
2875 break;
2876 case glslang::EOpDPdy:
2877 unaryOp = spv::OpDPdy;
2878 break;
2879 case glslang::EOpFwidth:
2880 unaryOp = spv::OpFwidth;
2881 break;
2882 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07002883 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002884 unaryOp = spv::OpDPdxFine;
2885 break;
2886 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07002887 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002888 unaryOp = spv::OpDPdyFine;
2889 break;
2890 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07002891 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002892 unaryOp = spv::OpFwidthFine;
2893 break;
2894 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002895 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002896 unaryOp = spv::OpDPdxCoarse;
2897 break;
2898 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002899 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002900 unaryOp = spv::OpDPdyCoarse;
2901 break;
2902 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002903 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002904 unaryOp = spv::OpFwidthCoarse;
2905 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002906 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07002907 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08002908 libCall = spv::GLSLstd450InterpolateAtCentroid;
2909 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002910 case glslang::EOpAny:
2911 unaryOp = spv::OpAny;
2912 break;
2913 case glslang::EOpAll:
2914 unaryOp = spv::OpAll;
2915 break;
2916
2917 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002918 if (isFloat)
2919 libCall = spv::GLSLstd450FAbs;
2920 else
2921 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002922 break;
2923 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002924 if (isFloat)
2925 libCall = spv::GLSLstd450FSign;
2926 else
2927 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002928 break;
2929
John Kessenichfc51d282015-08-19 13:34:18 -06002930 case glslang::EOpAtomicCounterIncrement:
2931 case glslang::EOpAtomicCounterDecrement:
2932 case glslang::EOpAtomicCounter:
2933 {
2934 // Handle all of the atomics in one place, in createAtomicOperation()
2935 std::vector<spv::Id> operands;
2936 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002937 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002938 }
2939
John Kessenichfc51d282015-08-19 13:34:18 -06002940 case glslang::EOpBitFieldReverse:
2941 unaryOp = spv::OpBitReverse;
2942 break;
2943 case glslang::EOpBitCount:
2944 unaryOp = spv::OpBitCount;
2945 break;
2946 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002947 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002948 break;
2949 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002950 if (isUnsigned)
2951 libCall = spv::GLSLstd450FindUMsb;
2952 else
2953 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002954 break;
2955
John Kessenich140f3df2015-06-26 16:58:36 -06002956 default:
2957 return 0;
2958 }
2959
2960 spv::Id id;
2961 if (libCall >= 0) {
2962 std::vector<spv::Id> args;
2963 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07002964 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06002965 } else
2966 id = builder.createUnaryOp(unaryOp, typeId, operand);
2967
John Kessenich32cfd492016-02-02 12:37:46 -07002968 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002969}
2970
John Kessenich7a53f762016-01-20 11:19:27 -07002971// Create a unary operation on a matrix
2972spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
2973{
2974 // Handle unary operations vector by vector.
2975 // The result type is the same type as the original type.
2976 // The algorithm is to:
2977 // - break the matrix into vectors
2978 // - apply the operation to each vector
2979 // - make a matrix out the vector results
2980
2981 // get the types sorted out
2982 int numCols = builder.getNumColumns(operand);
2983 int numRows = builder.getNumRows(operand);
2984 spv::Id scalarType = builder.getScalarTypeId(typeId);
2985 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2986 std::vector<spv::Id> results;
2987
2988 // do each vector op
2989 for (int c = 0; c < numCols; ++c) {
2990 std::vector<unsigned int> indexes;
2991 indexes.push_back(c);
2992 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
2993 results.push_back(builder.createUnaryOp(op, vecType, vec));
2994 builder.setPrecision(results.back(), precision);
2995 }
2996
2997 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002998 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07002999}
3000
John Kessenich140f3df2015-06-26 16:58:36 -06003001spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3002{
3003 spv::Op convOp = spv::OpNop;
3004 spv::Id zero = 0;
3005 spv::Id one = 0;
3006
3007 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3008
3009 switch (op) {
3010 case glslang::EOpConvIntToBool:
3011 case glslang::EOpConvUintToBool:
3012 zero = builder.makeUintConstant(0);
3013 zero = makeSmearedConstant(zero, vectorSize);
3014 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3015
3016 case glslang::EOpConvFloatToBool:
3017 zero = builder.makeFloatConstant(0.0F);
3018 zero = makeSmearedConstant(zero, vectorSize);
3019 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3020
3021 case glslang::EOpConvDoubleToBool:
3022 zero = builder.makeDoubleConstant(0.0);
3023 zero = makeSmearedConstant(zero, vectorSize);
3024 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3025
3026 case glslang::EOpConvBoolToFloat:
3027 convOp = spv::OpSelect;
3028 zero = builder.makeFloatConstant(0.0);
3029 one = builder.makeFloatConstant(1.0);
3030 break;
3031 case glslang::EOpConvBoolToDouble:
3032 convOp = spv::OpSelect;
3033 zero = builder.makeDoubleConstant(0.0);
3034 one = builder.makeDoubleConstant(1.0);
3035 break;
3036 case glslang::EOpConvBoolToInt:
3037 zero = builder.makeIntConstant(0);
3038 one = builder.makeIntConstant(1);
3039 convOp = spv::OpSelect;
3040 break;
3041 case glslang::EOpConvBoolToUint:
3042 zero = builder.makeUintConstant(0);
3043 one = builder.makeUintConstant(1);
3044 convOp = spv::OpSelect;
3045 break;
3046
3047 case glslang::EOpConvIntToFloat:
3048 case glslang::EOpConvIntToDouble:
3049 convOp = spv::OpConvertSToF;
3050 break;
3051
3052 case glslang::EOpConvUintToFloat:
3053 case glslang::EOpConvUintToDouble:
3054 convOp = spv::OpConvertUToF;
3055 break;
3056
3057 case glslang::EOpConvDoubleToFloat:
3058 case glslang::EOpConvFloatToDouble:
3059 convOp = spv::OpFConvert;
3060 break;
3061
3062 case glslang::EOpConvFloatToInt:
3063 case glslang::EOpConvDoubleToInt:
3064 convOp = spv::OpConvertFToS;
3065 break;
3066
3067 case glslang::EOpConvUintToInt:
3068 case glslang::EOpConvIntToUint:
3069 convOp = spv::OpBitcast;
3070 break;
3071
3072 case glslang::EOpConvFloatToUint:
3073 case glslang::EOpConvDoubleToUint:
3074 convOp = spv::OpConvertFToU;
3075 break;
3076 default:
3077 break;
3078 }
3079
3080 spv::Id result = 0;
3081 if (convOp == spv::OpNop)
3082 return result;
3083
3084 if (convOp == spv::OpSelect) {
3085 zero = makeSmearedConstant(zero, vectorSize);
3086 one = makeSmearedConstant(one, vectorSize);
3087 result = builder.createTriOp(convOp, destType, operand, one, zero);
3088 } else
3089 result = builder.createUnaryOp(convOp, destType, operand);
3090
John Kessenich32cfd492016-02-02 12:37:46 -07003091 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003092}
3093
3094spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3095{
3096 if (vectorSize == 0)
3097 return constant;
3098
3099 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3100 std::vector<spv::Id> components;
3101 for (int c = 0; c < vectorSize; ++c)
3102 components.push_back(constant);
3103 return builder.makeCompositeConstant(vectorTypeId, components);
3104}
3105
John Kessenich426394d2015-07-23 10:22:48 -06003106// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08003107spv::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 -06003108{
3109 spv::Op opCode = spv::OpNop;
3110
3111 switch (op) {
3112 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003113 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003114 opCode = spv::OpAtomicIAdd;
3115 break;
3116 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003117 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003118 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003119 break;
3120 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003121 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003122 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003123 break;
3124 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003125 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003126 opCode = spv::OpAtomicAnd;
3127 break;
3128 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003129 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003130 opCode = spv::OpAtomicOr;
3131 break;
3132 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003133 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003134 opCode = spv::OpAtomicXor;
3135 break;
3136 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003137 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003138 opCode = spv::OpAtomicExchange;
3139 break;
3140 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003141 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003142 opCode = spv::OpAtomicCompareExchange;
3143 break;
3144 case glslang::EOpAtomicCounterIncrement:
3145 opCode = spv::OpAtomicIIncrement;
3146 break;
3147 case glslang::EOpAtomicCounterDecrement:
3148 opCode = spv::OpAtomicIDecrement;
3149 break;
3150 case glslang::EOpAtomicCounter:
3151 opCode = spv::OpAtomicLoad;
3152 break;
3153 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003154 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003155 break;
3156 }
3157
3158 // Sort out the operands
3159 // - mapping from glslang -> SPV
3160 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003161 // - compare-exchange swaps the value and comparator
3162 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003163 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3164 auto opIt = operands.begin(); // walk the glslang operands
3165 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003166 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3167 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3168 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003169 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3170 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003171 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003172 spvAtomicOperands.push_back(*(opIt + 1));
3173 spvAtomicOperands.push_back(*opIt);
3174 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003175 }
John Kessenich426394d2015-07-23 10:22:48 -06003176
John Kessenich3e60a6f2015-09-14 22:45:16 -06003177 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003178 for (; opIt != operands.end(); ++opIt)
3179 spvAtomicOperands.push_back(*opIt);
3180
3181 return builder.createOp(opCode, typeId, spvAtomicOperands);
3182}
3183
John Kessenich5e4b1242015-08-06 22:53:06 -06003184spv::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 -06003185{
John Kessenich5e4b1242015-08-06 22:53:06 -06003186 bool isUnsigned = typeProxy == glslang::EbtUint;
3187 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3188
John Kessenich140f3df2015-06-26 16:58:36 -06003189 spv::Op opCode = spv::OpNop;
3190 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003191 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003192 spv::Id typeId0 = 0;
3193 if (consumedOperands > 0)
3194 typeId0 = builder.getTypeId(operands[0]);
3195 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003196
3197 switch (op) {
3198 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003199 if (isFloat)
3200 libCall = spv::GLSLstd450FMin;
3201 else if (isUnsigned)
3202 libCall = spv::GLSLstd450UMin;
3203 else
3204 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003205 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003206 break;
3207 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003208 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003209 break;
3210 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003211 if (isFloat)
3212 libCall = spv::GLSLstd450FMax;
3213 else if (isUnsigned)
3214 libCall = spv::GLSLstd450UMax;
3215 else
3216 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003217 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003218 break;
3219 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003220 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003221 break;
3222 case glslang::EOpDot:
3223 opCode = spv::OpDot;
3224 break;
3225 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003226 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003227 break;
3228
3229 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003230 if (isFloat)
3231 libCall = spv::GLSLstd450FClamp;
3232 else if (isUnsigned)
3233 libCall = spv::GLSLstd450UClamp;
3234 else
3235 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003236 builder.promoteScalar(precision, operands.front(), operands[1]);
3237 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003238 break;
3239 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003240 if (isFloat)
3241 libCall = spv::GLSLstd450FMix;
3242 else
3243 libCall = spv::GLSLstd450IMix;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003244 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003245 break;
3246 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003247 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003248 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003249 break;
3250 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003251 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003252 builder.promoteScalar(precision, operands[0], operands[2]);
3253 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003254 break;
3255
3256 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003257 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003258 break;
3259 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003260 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003261 break;
3262 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003263 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003264 break;
3265 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003266 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003267 break;
3268 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003269 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003270 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003271 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003272 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003273 libCall = spv::GLSLstd450InterpolateAtSample;
3274 break;
3275 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003276 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003277 libCall = spv::GLSLstd450InterpolateAtOffset;
3278 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003279 case glslang::EOpAddCarry:
3280 opCode = spv::OpIAddCarry;
3281 typeId = builder.makeStructResultType(typeId0, typeId0);
3282 consumedOperands = 2;
3283 break;
3284 case glslang::EOpSubBorrow:
3285 opCode = spv::OpISubBorrow;
3286 typeId = builder.makeStructResultType(typeId0, typeId0);
3287 consumedOperands = 2;
3288 break;
3289 case glslang::EOpUMulExtended:
3290 opCode = spv::OpUMulExtended;
3291 typeId = builder.makeStructResultType(typeId0, typeId0);
3292 consumedOperands = 2;
3293 break;
3294 case glslang::EOpIMulExtended:
3295 opCode = spv::OpSMulExtended;
3296 typeId = builder.makeStructResultType(typeId0, typeId0);
3297 consumedOperands = 2;
3298 break;
3299 case glslang::EOpBitfieldExtract:
3300 if (isUnsigned)
3301 opCode = spv::OpBitFieldUExtract;
3302 else
3303 opCode = spv::OpBitFieldSExtract;
3304 break;
3305 case glslang::EOpBitfieldInsert:
3306 opCode = spv::OpBitFieldInsert;
3307 break;
3308
3309 case glslang::EOpFma:
3310 libCall = spv::GLSLstd450Fma;
3311 break;
3312 case glslang::EOpFrexp:
3313 libCall = spv::GLSLstd450FrexpStruct;
3314 if (builder.getNumComponents(operands[0]) == 1)
3315 frexpIntType = builder.makeIntegerType(32, true);
3316 else
3317 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3318 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3319 consumedOperands = 1;
3320 break;
3321 case glslang::EOpLdexp:
3322 libCall = spv::GLSLstd450Ldexp;
3323 break;
3324
John Kessenich140f3df2015-06-26 16:58:36 -06003325 default:
3326 return 0;
3327 }
3328
3329 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003330 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003331 // Use an extended instruction from the standard library.
3332 // Construct the call arguments, without modifying the original operands vector.
3333 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3334 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003335 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003336 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003337 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003338 case 0:
3339 // should all be handled by visitAggregate and createNoArgOperation
3340 assert(0);
3341 return 0;
3342 case 1:
3343 // should all be handled by createUnaryOperation
3344 assert(0);
3345 return 0;
3346 case 2:
3347 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3348 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003349 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003350 // anything 3 or over doesn't have l-value operands, so all should be consumed
3351 assert(consumedOperands == operands.size());
3352 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003353 break;
3354 }
3355 }
3356
John Kessenich55e7d112015-11-15 21:33:39 -07003357 // Decode the return types that were structures
3358 switch (op) {
3359 case glslang::EOpAddCarry:
3360 case glslang::EOpSubBorrow:
3361 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3362 id = builder.createCompositeExtract(id, typeId0, 0);
3363 break;
3364 case glslang::EOpUMulExtended:
3365 case glslang::EOpIMulExtended:
3366 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3367 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3368 break;
3369 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003370 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003371 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3372 id = builder.createCompositeExtract(id, typeId0, 0);
3373 break;
3374 default:
3375 break;
3376 }
3377
John Kessenich32cfd492016-02-02 12:37:46 -07003378 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003379}
3380
3381// Intrinsics with no arguments, no return value, and no precision.
3382spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3383{
3384 // TODO: get the barrier operands correct
3385
3386 switch (op) {
3387 case glslang::EOpEmitVertex:
3388 builder.createNoResultOp(spv::OpEmitVertex);
3389 return 0;
3390 case glslang::EOpEndPrimitive:
3391 builder.createNoResultOp(spv::OpEndPrimitive);
3392 return 0;
3393 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003394 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3395 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003396 return 0;
3397 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003398 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003399 return 0;
3400 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003401 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003402 return 0;
3403 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003404 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003405 return 0;
3406 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003407 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003408 return 0;
3409 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003410 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003411 return 0;
3412 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003413 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003414 return 0;
3415 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003416 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003417 return 0;
3418 }
3419}
3420
3421spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3422{
John Kessenich2f273362015-07-18 22:34:27 -06003423 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003424 spv::Id id;
3425 if (symbolValues.end() != iter) {
3426 id = iter->second;
3427 return id;
3428 }
3429
3430 // it was not found, create it
3431 id = createSpvVariable(symbol);
3432 symbolValues[symbol->getId()] = id;
3433
3434 if (! symbol->getType().isStruct()) {
3435 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003436 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003437 if (symbol->getQualifier().hasLocation())
3438 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3439 if (symbol->getQualifier().hasIndex())
3440 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3441 if (symbol->getQualifier().hasComponent())
3442 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3443 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003444 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003445 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003446 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003447 if (symbol->getQualifier().hasXfbBuffer())
3448 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3449 if (symbol->getQualifier().hasXfbOffset())
3450 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3451 }
3452 }
3453
John Kesseniche0b6cad2015-12-24 10:30:13 -07003454 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenich92187592016-02-01 13:45:25 -07003455 if (symbol->getQualifier().hasStream()) {
3456 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003457 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003458 }
John Kessenich140f3df2015-06-26 16:58:36 -06003459 if (symbol->getQualifier().hasSet())
3460 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3461 if (symbol->getQualifier().hasBinding())
3462 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3463 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003464 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003465 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003466 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003467 if (symbol->getQualifier().hasXfbBuffer())
3468 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3469 }
3470
3471 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003472 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003473 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003474 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003475
John Kessenich140f3df2015-06-26 16:58:36 -06003476 return id;
3477}
3478
John Kessenich55e7d112015-11-15 21:33:39 -07003479// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003480void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3481{
3482 if (dec != spv::BadValue)
3483 builder.addDecoration(id, dec);
3484}
3485
John Kessenich55e7d112015-11-15 21:33:39 -07003486// If 'dec' is valid, add a one-operand decoration to an object
3487void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3488{
3489 if (dec != spv::BadValue)
3490 builder.addDecoration(id, dec, value);
3491}
3492
3493// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003494void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3495{
3496 if (dec != spv::BadValue)
3497 builder.addMemberDecoration(id, (unsigned)member, dec);
3498}
3499
John Kessenich92187592016-02-01 13:45:25 -07003500// If 'dec' is valid, add a one-operand decoration to a struct member
3501void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3502{
3503 if (dec != spv::BadValue)
3504 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3505}
3506
John Kessenich55e7d112015-11-15 21:33:39 -07003507// Make a full tree of instructions to build a SPIR-V specialization constant,
3508// or regularly constant if possible.
3509//
3510// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3511//
3512// Recursively walk the nodes. The nodes form a tree whose leaves are
3513// regular constants, which themselves are trees that createSpvConstant()
3514// recursively walks. So, this function walks the "top" of the tree:
3515// - emit specialization constant-building instructions for specConstant
3516// - when running into a non-spec-constant, switch to createSpvConstant()
3517spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3518{
3519 assert(node.getQualifier().storage == glslang::EvqConst);
3520
3521 // hand off to the non-spec-constant path
3522 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3523 int nextConst = 0;
3524 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3525}
3526
John Kessenich140f3df2015-06-26 16:58:36 -06003527// Use 'consts' as the flattened glslang source of scalar constants to recursively
3528// build the aggregate SPIR-V constant.
3529//
3530// If there are not enough elements present in 'consts', 0 will be substituted;
3531// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3532//
John Kessenich55e7d112015-11-15 21:33:39 -07003533spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003534{
3535 // vector of constants for SPIR-V
3536 std::vector<spv::Id> spvConsts;
3537
3538 // Type is used for struct and array constants
3539 spv::Id typeId = convertGlslangToSpvType(glslangType);
3540
3541 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003542 glslang::TType elementType(glslangType, 0);
3543 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003544 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003545 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003546 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003547 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003548 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003549 } else if (glslangType.getStruct()) {
3550 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3551 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003552 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003553 } else if (glslangType.isVector()) {
3554 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3555 bool zero = nextConst >= consts.size();
3556 switch (glslangType.getBasicType()) {
3557 case glslang::EbtInt:
3558 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3559 break;
3560 case glslang::EbtUint:
3561 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3562 break;
3563 case glslang::EbtFloat:
3564 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3565 break;
3566 case glslang::EbtDouble:
3567 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3568 break;
3569 case glslang::EbtBool:
3570 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3571 break;
3572 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003573 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003574 break;
3575 }
3576 ++nextConst;
3577 }
3578 } else {
3579 // we have a non-aggregate (scalar) constant
3580 bool zero = nextConst >= consts.size();
3581 spv::Id scalar = 0;
3582 switch (glslangType.getBasicType()) {
3583 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003584 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003585 break;
3586 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003587 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003588 break;
3589 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003590 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003591 break;
3592 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003593 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003594 break;
3595 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003596 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003597 break;
3598 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003599 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003600 break;
3601 }
3602 ++nextConst;
3603 return scalar;
3604 }
3605
3606 return builder.makeCompositeConstant(typeId, spvConsts);
3607}
3608
John Kessenich7c1aa102015-10-15 13:29:11 -06003609// Return true if the node is a constant or symbol whose reading has no
3610// non-trivial observable cost or effect.
3611bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3612{
3613 // don't know what this is
3614 if (node == nullptr)
3615 return false;
3616
3617 // a constant is safe
3618 if (node->getAsConstantUnion() != nullptr)
3619 return true;
3620
3621 // not a symbol means non-trivial
3622 if (node->getAsSymbolNode() == nullptr)
3623 return false;
3624
3625 // a symbol, depends on what's being read
3626 switch (node->getType().getQualifier().storage) {
3627 case glslang::EvqTemporary:
3628 case glslang::EvqGlobal:
3629 case glslang::EvqIn:
3630 case glslang::EvqInOut:
3631 case glslang::EvqConst:
3632 case glslang::EvqConstReadOnly:
3633 case glslang::EvqUniform:
3634 return true;
3635 default:
3636 return false;
3637 }
3638}
3639
3640// A node is trivial if it is a single operation with no side effects.
3641// Error on the side of saying non-trivial.
3642// Return true if trivial.
3643bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3644{
3645 if (node == nullptr)
3646 return false;
3647
3648 // symbols and constants are trivial
3649 if (isTrivialLeaf(node))
3650 return true;
3651
3652 // otherwise, it needs to be a simple operation or one or two leaf nodes
3653
3654 // not a simple operation
3655 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3656 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3657 if (binaryNode == nullptr && unaryNode == nullptr)
3658 return false;
3659
3660 // not on leaf nodes
3661 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3662 return false;
3663
3664 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3665 return false;
3666 }
3667
3668 switch (node->getAsOperator()->getOp()) {
3669 case glslang::EOpLogicalNot:
3670 case glslang::EOpConvIntToBool:
3671 case glslang::EOpConvUintToBool:
3672 case glslang::EOpConvFloatToBool:
3673 case glslang::EOpConvDoubleToBool:
3674 case glslang::EOpEqual:
3675 case glslang::EOpNotEqual:
3676 case glslang::EOpLessThan:
3677 case glslang::EOpGreaterThan:
3678 case glslang::EOpLessThanEqual:
3679 case glslang::EOpGreaterThanEqual:
3680 case glslang::EOpIndexDirect:
3681 case glslang::EOpIndexDirectStruct:
3682 case glslang::EOpLogicalXor:
3683 case glslang::EOpAny:
3684 case glslang::EOpAll:
3685 return true;
3686 default:
3687 return false;
3688 }
3689}
3690
3691// Emit short-circuiting code, where 'right' is never evaluated unless
3692// the left side is true (for &&) or false (for ||).
3693spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3694{
3695 spv::Id boolTypeId = builder.makeBoolType();
3696
3697 // emit left operand
3698 builder.clearAccessChain();
3699 left.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003700 spv::Id leftId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003701
3702 // Operands to accumulate OpPhi operands
3703 std::vector<spv::Id> phiOperands;
3704 // accumulate left operand's phi information
3705 phiOperands.push_back(leftId);
3706 phiOperands.push_back(builder.getBuildPoint()->getId());
3707
3708 // Make the two kinds of operation symmetric with a "!"
3709 // || => emit "if (! left) result = right"
3710 // && => emit "if ( left) result = right"
3711 //
3712 // TODO: this runtime "not" for || could be avoided by adding functionality
3713 // to 'builder' to have an "else" without an "then"
3714 if (op == glslang::EOpLogicalOr)
3715 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3716
3717 // make an "if" based on the left value
3718 spv::Builder::If ifBuilder(leftId, builder);
3719
3720 // emit right operand as the "then" part of the "if"
3721 builder.clearAccessChain();
3722 right.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003723 spv::Id rightId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003724
3725 // accumulate left operand's phi information
3726 phiOperands.push_back(rightId);
3727 phiOperands.push_back(builder.getBuildPoint()->getId());
3728
3729 // finish the "if"
3730 ifBuilder.makeEndIf();
3731
3732 // phi together the two results
3733 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3734}
3735
John Kessenich140f3df2015-06-26 16:58:36 -06003736}; // end anonymous namespace
3737
3738namespace glslang {
3739
John Kessenich68d78fd2015-07-12 19:28:10 -06003740void GetSpirvVersion(std::string& version)
3741{
John Kessenich9e55f632015-07-15 10:03:39 -06003742 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003743 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003744 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003745 version = buf;
3746}
3747
John Kessenich140f3df2015-06-26 16:58:36 -06003748// Write SPIR-V out to a binary file
3749void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3750{
3751 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003752 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003753 for (int i = 0; i < (int)spirv.size(); ++i) {
3754 unsigned int word = spirv[i];
3755 out.write((const char*)&word, 4);
3756 }
3757 out.close();
3758}
3759
3760//
3761// Set up the glslang traversal
3762//
3763void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3764{
3765 TIntermNode* root = intermediate.getTreeRoot();
3766
3767 if (root == 0)
3768 return;
3769
3770 glslang::GetThreadPoolAllocator().push();
3771
3772 TGlslangToSpvTraverser it(&intermediate);
3773
3774 root->traverse(&it);
3775
3776 it.dumpSpv(spirv);
3777
3778 glslang::GetThreadPoolAllocator().pop();
3779}
3780
3781}; // end namespace glslang