blob: 0fff30e97bff6334d591cc2e52c76b3598320e22 [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
88 void dumpSpv(std::vector<unsigned int>& out) { builder.dump(out); }
89
90protected:
91 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
92 spv::Id getSampledType(const glslang::TSampler&);
93 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenich31ed4832015-09-09 17:51:38 -060094 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout);
95 bool requiresExplicitLayout(const glslang::TType& type) const;
Jason Ekstrand54aedf12015-09-05 09:50:58 -070096 int getArrayStride(const glslang::TType& arrayType);
97 int getMatrixStride(const glslang::TType& matrixType);
John Kessenich5e4b1242015-08-06 22:53:06 -060098 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset);
John Kessenich140f3df2015-06-26 16:58:36 -060099
100 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
101 void makeFunctions(const glslang::TIntermSequence&);
102 void makeGlobalInitializers(const glslang::TIntermSequence&);
103 void visitFunctions(const glslang::TIntermSequence&);
104 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800105 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600106 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
107 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600108 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
109
110 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
Rex Xu04db3f52015-09-16 11:44:02 +0800111 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600112 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
113 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800114 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 -0600115 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 -0600116 spv::Id createNoArgOperation(glslang::TOperator op);
117 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
118 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700119 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600120 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700121 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
122 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600123 bool isTrivialLeaf(const glslang::TIntermTyped* node);
124 bool isTrivial(const glslang::TIntermTyped* node);
125 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600126
127 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700128 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600129 int sequenceDepth;
130
131 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
132 spv::Builder builder;
133 bool inMain;
134 bool mainTerminated;
135 bool linkageOnly;
136 const glslang::TIntermediate* glslangIntermediate;
137 spv::Id stdBuiltins;
138
John Kessenich2f273362015-07-18 22:34:27 -0600139 std::unordered_map<int, spv::Id> symbolValues;
140 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
141 std::unordered_map<std::string, spv::Function*> functionMap;
142 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap;
143 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 -0600144 std::stack<bool> breakForLoop; // false means break for switch
145 std::stack<glslang::TIntermTyped*> loopTerminal; // code from the last part of a for loop: for(...; ...; terminal), needed for e.g., continue };
146};
147
148//
149// Helper functions for translating glslang representations to SPIR-V enumerants.
150//
151
152// Translate glslang profile to SPIR-V source language.
153spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
154{
155 switch (profile) {
156 case ENoProfile:
157 case ECoreProfile:
158 case ECompatibilityProfile:
159 return spv::SourceLanguageGLSL;
160 case EEsProfile:
161 return spv::SourceLanguageESSL;
162 default:
163 return spv::SourceLanguageUnknown;
164 }
165}
166
167// Translate glslang language (stage) to SPIR-V execution model.
168spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
169{
170 switch (stage) {
171 case EShLangVertex: return spv::ExecutionModelVertex;
172 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
173 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
174 case EShLangGeometry: return spv::ExecutionModelGeometry;
175 case EShLangFragment: return spv::ExecutionModelFragment;
176 case EShLangCompute: return spv::ExecutionModelGLCompute;
177 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700178 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600179 return spv::ExecutionModelFragment;
180 }
181}
182
183// Translate glslang type to SPIR-V storage class.
184spv::StorageClass TranslateStorageClass(const glslang::TType& type)
185{
186 if (type.getQualifier().isPipeInput())
187 return spv::StorageClassInput;
188 else if (type.getQualifier().isPipeOutput())
189 return spv::StorageClassOutput;
190 else if (type.getQualifier().isUniformOrBuffer()) {
191 if (type.getBasicType() == glslang::EbtBlock)
192 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800193 else if (type.getBasicType() == glslang::EbtAtomicUint)
194 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600195 else
196 return spv::StorageClassUniformConstant;
197 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
198 } else {
199 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700200 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
201 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600202 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
203 case glslang::EvqTemporary: return spv::StorageClassFunction;
204 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700205 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600206 return spv::StorageClassFunction;
207 }
208 }
209}
210
211// Translate glslang sampler type to SPIR-V dimensionality.
212spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
213{
214 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700215 case glslang::Esd1D: return spv::Dim1D;
216 case glslang::Esd2D: return spv::Dim2D;
217 case glslang::Esd3D: return spv::Dim3D;
218 case glslang::EsdCube: return spv::DimCube;
219 case glslang::EsdRect: return spv::DimRect;
220 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich140f3df2015-06-26 16:58:36 -0600221 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700222 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600223 return spv::Dim2D;
224 }
225}
226
227// Translate glslang type to SPIR-V precision decorations.
228spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
229{
230 switch (type.getQualifier().precision) {
John Kessenich5e4b1242015-08-06 22:53:06 -0600231 case glslang::EpqLow: return spv::DecorationRelaxedPrecision; // TODO: Map instead to 16-bit types?
232 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
233 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600234 default:
235 return spv::NoPrecision;
236 }
237}
238
239// Translate glslang type to SPIR-V block decorations.
240spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
241{
242 if (type.getBasicType() == glslang::EbtBlock) {
243 switch (type.getQualifier().storage) {
244 case glslang::EvqUniform: return spv::DecorationBlock;
245 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
246 case glslang::EvqVaryingIn: return spv::DecorationBlock;
247 case glslang::EvqVaryingOut: return spv::DecorationBlock;
248 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700249 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600250 break;
251 }
252 }
253
254 return (spv::Decoration)spv::BadValue;
255}
256
257// Translate glslang type to SPIR-V layout decorations.
258spv::Decoration TranslateLayoutDecoration(const glslang::TType& type)
259{
260 if (type.isMatrix()) {
261 switch (type.getQualifier().layoutMatrix) {
262 case glslang::ElmRowMajor:
263 return spv::DecorationRowMajor;
264 default:
265 return spv::DecorationColMajor;
266 }
267 } else {
268 switch (type.getBasicType()) {
269 default:
270 return (spv::Decoration)spv::BadValue;
271 break;
272 case glslang::EbtBlock:
273 switch (type.getQualifier().storage) {
274 case glslang::EvqUniform:
275 case glslang::EvqBuffer:
276 switch (type.getQualifier().layoutPacking) {
277 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600278 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
279 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600280 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600281 }
282 case glslang::EvqVaryingIn:
283 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700284 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600285 return (spv::Decoration)spv::BadValue;
286 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700287 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600288 return (spv::Decoration)spv::BadValue;
289 }
290 }
291 }
292}
293
294// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700295// Returns spv::Decoration(spv::BadValue) when no decoration
296// should be applied.
John Kessenich140f3df2015-06-26 16:58:36 -0600297spv::Decoration TranslateInterpolationDecoration(const glslang::TType& type)
298{
John Kessenich55e7d112015-11-15 21:33:39 -0700299 if (type.getQualifier().smooth) {
300 // Smooth decoration doesn't exist in SPIR-V 1.0
301 return (spv::Decoration)spv::BadValue;
302 }
John Kessenich140f3df2015-06-26 16:58:36 -0600303 if (type.getQualifier().nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700304 return spv::DecorationNoPerspective;
John Kessenich140f3df2015-06-26 16:58:36 -0600305 else if (type.getQualifier().patch)
306 return spv::DecorationPatch;
307 else if (type.getQualifier().flat)
308 return spv::DecorationFlat;
309 else if (type.getQualifier().centroid)
310 return spv::DecorationCentroid;
311 else if (type.getQualifier().sample)
312 return spv::DecorationSample;
313 else
314 return (spv::Decoration)spv::BadValue;
315}
316
317// If glslang type is invaraiant, return SPIR-V invariant decoration.
318spv::Decoration TranslateInvariantDecoration(const glslang::TType& type)
319{
320 if (type.getQualifier().invariant)
321 return spv::DecorationInvariant;
322 else
323 return (spv::Decoration)spv::BadValue;
324}
325
326// Translate glslang built-in variable to SPIR-V built in decoration.
327spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
328{
329 switch (builtIn) {
330 case glslang::EbvPosition: return spv::BuiltInPosition;
331 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600332 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
333 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
334 case glslang::EbvVertexId: return spv::BuiltInVertexId;
335 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenichda581a22015-10-14 14:10:30 -0600336 case glslang::EbvBaseVertex:
337 case glslang::EbvBaseInstance:
338 case glslang::EbvDrawId:
339 // TODO: Add SPIR-V builtin ID.
340 spv::MissingFunctionality("Draw parameters");
341 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
343 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
344 case glslang::EbvLayer: return spv::BuiltInLayer;
345 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
346 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
347 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
348 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
349 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
350 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
351 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
352 case glslang::EbvFace: return spv::BuiltInFrontFacing;
353 case glslang::EbvSampleId: return spv::BuiltInSampleId;
354 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
355 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
John Kessenich140f3df2015-06-26 16:58:36 -0600356 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
357 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
358 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
359 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
360 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
361 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
362 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
363 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
364 default: return (spv::BuiltIn)spv::BadValue;
365 }
366}
367
Rex Xufc618912015-09-09 16:42:49 +0800368// Translate glslang image layout format to SPIR-V image format.
369spv::ImageFormat TranslateImageFormat(const glslang::TType& type)
370{
371 assert(type.getBasicType() == glslang::EbtSampler);
372
373 switch (type.getQualifier().layoutFormat) {
374 case glslang::ElfNone: return spv::ImageFormatUnknown;
375 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
376 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
377 case glslang::ElfR32f: return spv::ImageFormatR32f;
378 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
379 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
380 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
381 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
382 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
383 case glslang::ElfR16f: return spv::ImageFormatR16f;
384 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
385 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
386 case glslang::ElfRg16: return spv::ImageFormatRg16;
387 case glslang::ElfRg8: return spv::ImageFormatRg8;
388 case glslang::ElfR16: return spv::ImageFormatR16;
389 case glslang::ElfR8: return spv::ImageFormatR8;
390 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
391 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
392 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
393 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
394 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
395 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
396 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
397 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
398 case glslang::ElfR32i: return spv::ImageFormatR32i;
399 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
400 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
401 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
402 case glslang::ElfR16i: return spv::ImageFormatR16i;
403 case glslang::ElfR8i: return spv::ImageFormatR8i;
404 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
405 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
406 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
407 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
408 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
409 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
410 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
411 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
412 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
413 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
414 default: return (spv::ImageFormat)spv::BadValue;
415 }
416}
417
John Kessenich140f3df2015-06-26 16:58:36 -0600418//
419// Implement the TGlslangToSpvTraverser class.
420//
421
422TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
423 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700424 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600425 inMain(false), mainTerminated(false), linkageOnly(false),
426 glslangIntermediate(glslangIntermediate)
427{
428 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
429
430 builder.clearAccessChain();
431 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
432 stdBuiltins = builder.import("GLSL.std.450");
433 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
434 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700435 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600436
437 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600438 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
439 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600440 builder.addSourceExtension(it->c_str());
441
442 // Add the top-level modes for this shader.
443
444 if (glslangIntermediate->getXfbMode())
445 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
446
447 unsigned int mode;
448 switch (glslangIntermediate->getStage()) {
449 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600450 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600451 break;
452
453 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600454 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600455 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
456 break;
457
458 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600459 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600460 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700461 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
462 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
463 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600464 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600465 }
466 if (mode != spv::BadValue)
467 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
468
John Kesseniche6903322015-10-13 16:29:02 -0600469 switch (glslangIntermediate->getVertexSpacing()) {
470 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
471 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
472 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
473 default: mode = spv::BadValue; break;
474 }
475 if (mode != spv::BadValue)
476 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
477
478 switch (glslangIntermediate->getVertexOrder()) {
479 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
480 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
481 default: mode = spv::BadValue; break;
482 }
483 if (mode != spv::BadValue)
484 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
485
486 if (glslangIntermediate->getPointMode())
487 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600488 break;
489
490 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600491 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600492 switch (glslangIntermediate->getInputPrimitive()) {
493 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
494 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
495 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700496 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600497 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
498 default: mode = spv::BadValue; break;
499 }
500 if (mode != spv::BadValue)
501 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600502
John Kessenich140f3df2015-06-26 16:58:36 -0600503 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
504
505 switch (glslangIntermediate->getOutputPrimitive()) {
506 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
507 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
508 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
509 default: mode = spv::BadValue; break;
510 }
511 if (mode != spv::BadValue)
512 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
513 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
514 break;
515
516 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600517 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600518 if (glslangIntermediate->getPixelCenterInteger())
519 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600520
John Kessenich140f3df2015-06-26 16:58:36 -0600521 if (glslangIntermediate->getOriginUpperLeft())
522 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600523 else
524 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600525
526 if (glslangIntermediate->getEarlyFragmentTests())
527 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
528
529 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600530 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
531 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
532 default: mode = spv::BadValue; break;
533 }
534 if (mode != spv::BadValue)
535 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
536
537 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
538 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600539 break;
540
541 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600542 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600543 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
544 glslangIntermediate->getLocalSize(1),
545 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600546 break;
547
548 default:
549 break;
550 }
551
552}
553
554TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
555{
556 if (! mainTerminated) {
557 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
558 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600559 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600560 }
561}
562
563//
564// Implement the traversal functions.
565//
566// Return true from interior nodes to have the external traversal
567// continue on to children. Return false if children were
568// already processed.
569//
570
571//
572// Symbols can turn into
573// - uniform/input reads
574// - output writes
575// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
576// - something simple that degenerates into the last bullet
577//
578void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
579{
580 // getSymbolId() will set up all the IO decorations on the first call.
581 // Formal function parameters were mapped during makeFunctions().
582 spv::Id id = getSymbolId(symbol);
583
584 if (! linkageOnly) {
585 // Prepare to generate code for the access
586
587 // L-value chains will be computed left to right. We're on the symbol now,
588 // which is the left-most part of the access chain, so now is "clear" time,
589 // followed by setting the base.
590 builder.clearAccessChain();
591
592 // For now, we consider all user variables as being in memory, so they are pointers,
593 // except for "const in" arguments to a function, which are an intermediate object.
594 // See comments in handleUserFunctionCall().
595 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
596 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
597 builder.setAccessChainRValue(id);
598 else
599 builder.setAccessChainLValue(id);
John Kessenich55e7d112015-11-15 21:33:39 -0700600 } else {
601 // finish off the entry-point SPV instruction by adding the Input/Output <id>
602 spv::StorageClass sc = builder.getStorageClass(id);
603 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
604 entryPoint->addIdOperand(id);
John Kessenich140f3df2015-06-26 16:58:36 -0600605 }
606}
607
608bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
609{
610 // First, handle special cases
611 switch (node->getOp()) {
612 case glslang::EOpAssign:
613 case glslang::EOpAddAssign:
614 case glslang::EOpSubAssign:
615 case glslang::EOpMulAssign:
616 case glslang::EOpVectorTimesMatrixAssign:
617 case glslang::EOpVectorTimesScalarAssign:
618 case glslang::EOpMatrixTimesScalarAssign:
619 case glslang::EOpMatrixTimesMatrixAssign:
620 case glslang::EOpDivAssign:
621 case glslang::EOpModAssign:
622 case glslang::EOpAndAssign:
623 case glslang::EOpInclusiveOrAssign:
624 case glslang::EOpExclusiveOrAssign:
625 case glslang::EOpLeftShiftAssign:
626 case glslang::EOpRightShiftAssign:
627 // A bin-op assign "a += b" means the same thing as "a = a + b"
628 // where a is evaluated before b. For a simple assignment, GLSL
629 // says to evaluate the left before the right. So, always, left
630 // node then right node.
631 {
632 // get the left l-value, save it away
633 builder.clearAccessChain();
634 node->getLeft()->traverse(this);
635 spv::Builder::AccessChain lValue = builder.getAccessChain();
636
637 // evaluate the right
638 builder.clearAccessChain();
639 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600640 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600641
642 if (node->getOp() != glslang::EOpAssign) {
643 // the left is also an r-value
644 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600645 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600646
647 // do the operation
648 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
649 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
650 node->getType().getBasicType());
651
652 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700653 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600654 }
655
656 // store the result
657 builder.setAccessChain(lValue);
658 builder.accessChainStore(rValue);
659
660 // assignments are expressions having an rValue after they are evaluated...
661 builder.clearAccessChain();
662 builder.setAccessChainRValue(rValue);
663 }
664 return false;
665 case glslang::EOpIndexDirect:
666 case glslang::EOpIndexDirectStruct:
667 {
668 // Get the left part of the access chain.
669 node->getLeft()->traverse(this);
670
671 // Add the next element in the chain
672
John Kessenich55e7d112015-11-15 21:33:39 -0700673 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600674 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
675 // This may be, e.g., an anonymous block-member selection, which generally need
676 // index remapping due to hidden members in anonymous blocks.
677 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700678 assert(remapper.size() > 0);
679 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600680 }
681
682 if (! node->getLeft()->getType().isArray() &&
683 node->getLeft()->getType().isVector() &&
684 node->getOp() == glslang::EOpIndexDirect) {
685 // This is essentially a hard-coded vector swizzle of size 1,
686 // so short circuit the access-chain stuff with a swizzle.
687 std::vector<unsigned> swizzle;
688 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600689 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600690 } else {
691 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600692 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600693 }
694 }
695 return false;
696 case glslang::EOpIndexIndirect:
697 {
698 // Structure or array or vector indirection.
699 // Will use native SPIR-V access-chain for struct and array indirection;
700 // matrices are arrays of vectors, so will also work for a matrix.
701 // Will use the access chain's 'component' for variable index into a vector.
702
703 // This adapter is building access chains left to right.
704 // Set up the access chain to the left.
705 node->getLeft()->traverse(this);
706
707 // save it so that computing the right side doesn't trash it
708 spv::Builder::AccessChain partial = builder.getAccessChain();
709
710 // compute the next index in the chain
711 builder.clearAccessChain();
712 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600713 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600714
715 // restore the saved access chain
716 builder.setAccessChain(partial);
717
718 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600719 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600720 else
John Kessenichfa668da2015-09-13 14:46:30 -0600721 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600722 }
723 return false;
724 case glslang::EOpVectorSwizzle:
725 {
726 node->getLeft()->traverse(this);
727 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
728 std::vector<unsigned> swizzle;
729 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
730 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600731 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600732 }
733 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600734 case glslang::EOpLogicalOr:
735 case glslang::EOpLogicalAnd:
736 {
737
738 // These may require short circuiting, but can sometimes be done as straight
739 // binary operations. The right operand must be short circuited if it has
740 // side effects, and should probably be if it is complex.
741 if (isTrivial(node->getRight()->getAsTyped()))
742 break; // handle below as a normal binary operation
743 // otherwise, we need to do dynamic short circuiting on the right operand
744 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
745 builder.clearAccessChain();
746 builder.setAccessChainRValue(result);
747 }
748 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600749 default:
750 break;
751 }
752
753 // Assume generic binary op...
754
755 // Get the operands
756 builder.clearAccessChain();
757 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600758 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600759
760 builder.clearAccessChain();
761 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600762 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600763
764 spv::Id result;
765 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
766
767 result = createBinaryOperation(node->getOp(), precision,
768 convertGlslangToSpvType(node->getType()), left, right,
769 node->getLeft()->getType().getBasicType());
770
771 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700772 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich140f3df2015-06-26 16:58:36 -0600773 } else {
774 builder.clearAccessChain();
775 builder.setAccessChainRValue(result);
776
777 return false;
778 }
779
780 return true;
781}
782
783bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
784{
John Kessenichfc51d282015-08-19 13:34:18 -0600785 spv::Id result = spv::NoResult;
786
787 // try texturing first
788 result = createImageTextureFunctionCall(node);
789 if (result != spv::NoResult) {
790 builder.clearAccessChain();
791 builder.setAccessChainRValue(result);
792
793 return false; // done with this node
794 }
795
796 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600797
798 if (node->getOp() == glslang::EOpArrayLength) {
799 // Quite special; won't want to evaluate the operand.
800
801 // Normal .length() would have been constant folded by the front-end.
802 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600803 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600804 assert(node->getOperand()->getType().isRuntimeSizedArray());
805 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
806 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600807 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
808 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600809
810 builder.clearAccessChain();
811 builder.setAccessChainRValue(length);
812
813 return false;
814 }
815
John Kessenichfc51d282015-08-19 13:34:18 -0600816 // Start by evaluating the operand
817
John Kessenich140f3df2015-06-26 16:58:36 -0600818 builder.clearAccessChain();
819 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800820
Rex Xufc618912015-09-09 16:42:49 +0800821 spv::Id operand = spv::NoResult;
822
823 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
824 node->getOp() == glslang::EOpAtomicCounterDecrement ||
825 node->getOp() == glslang::EOpAtomicCounter)
826 operand = builder.accessChainGetLValue(); // Special case l-value operands
827 else
Rex Xu30f92582015-09-14 10:38:56 +0800828 operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600829
830 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
831
832 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600833 if (! result)
834 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600835
836 // if not, then possibly an operation
837 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700838 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600839
840 if (result) {
841 builder.clearAccessChain();
842 builder.setAccessChainRValue(result);
843
844 return false; // done with this node
845 }
846
847 // it must be a special case, check...
848 switch (node->getOp()) {
849 case glslang::EOpPostIncrement:
850 case glslang::EOpPostDecrement:
851 case glslang::EOpPreIncrement:
852 case glslang::EOpPreDecrement:
853 {
854 // we need the integer value "1" or the floating point "1.0" to add/subtract
855 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
856 builder.makeFloatConstant(1.0F) :
857 builder.makeIntConstant(1);
858 glslang::TOperator op;
859 if (node->getOp() == glslang::EOpPreIncrement ||
860 node->getOp() == glslang::EOpPostIncrement)
861 op = glslang::EOpAdd;
862 else
863 op = glslang::EOpSub;
864
865 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
866 convertGlslangToSpvType(node->getType()), operand, one,
867 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -0700868 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600869
870 // The result of operation is always stored, but conditionally the
871 // consumed result. The consumed result is always an r-value.
872 builder.accessChainStore(result);
873 builder.clearAccessChain();
874 if (node->getOp() == glslang::EOpPreIncrement ||
875 node->getOp() == glslang::EOpPreDecrement)
876 builder.setAccessChainRValue(result);
877 else
878 builder.setAccessChainRValue(operand);
879 }
880
881 return false;
882
883 case glslang::EOpEmitStreamVertex:
884 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
885 return false;
886 case glslang::EOpEndStreamPrimitive:
887 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
888 return false;
889
890 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700891 spv::MissingFunctionality("unknown glslang unary");
John Kessenich140f3df2015-06-26 16:58:36 -0600892 break;
893 }
894
895 return true;
896}
897
898bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
899{
John Kessenichfc51d282015-08-19 13:34:18 -0600900 spv::Id result = spv::NoResult;
901
902 // try texturing
903 result = createImageTextureFunctionCall(node);
904 if (result != spv::NoResult) {
905 builder.clearAccessChain();
906 builder.setAccessChainRValue(result);
907
908 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600909 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800910 // "imageStore" is a special case, which has no result
911 return false;
912 }
John Kessenichfc51d282015-08-19 13:34:18 -0600913
John Kessenich140f3df2015-06-26 16:58:36 -0600914 glslang::TOperator binOp = glslang::EOpNull;
915 bool reduceComparison = true;
916 bool isMatrix = false;
917 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600918 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600919
920 assert(node->getOp());
921
922 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
923
924 switch (node->getOp()) {
925 case glslang::EOpSequence:
926 {
927 if (preVisit)
928 ++sequenceDepth;
929 else
930 --sequenceDepth;
931
932 if (sequenceDepth == 1) {
933 // If this is the parent node of all the functions, we want to see them
934 // early, so all call points have actual SPIR-V functions to reference.
935 // In all cases, still let the traverser visit the children for us.
936 makeFunctions(node->getAsAggregate()->getSequence());
937
938 // Also, we want all globals initializers to go into the entry of main(), before
939 // anything else gets there, so visit out of order, doing them all now.
940 makeGlobalInitializers(node->getAsAggregate()->getSequence());
941
942 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
943 // so do them manually.
944 visitFunctions(node->getAsAggregate()->getSequence());
945
946 return false;
947 }
948
949 return true;
950 }
951 case glslang::EOpLinkerObjects:
952 {
953 if (visit == glslang::EvPreVisit)
954 linkageOnly = true;
955 else
956 linkageOnly = false;
957
958 return true;
959 }
960 case glslang::EOpComma:
961 {
962 // processing from left to right naturally leaves the right-most
963 // lying around in the access chain
964 glslang::TIntermSequence& glslangOperands = node->getSequence();
965 for (int i = 0; i < (int)glslangOperands.size(); ++i)
966 glslangOperands[i]->traverse(this);
967
968 return false;
969 }
970 case glslang::EOpFunction:
971 if (visit == glslang::EvPreVisit) {
972 if (isShaderEntrypoint(node)) {
973 inMain = true;
974 builder.setBuildPoint(shaderEntry->getLastBlock());
975 } else {
976 handleFunctionEntry(node);
977 }
978 } else {
979 if (inMain)
980 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -0600981 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600982 inMain = false;
983 }
984
985 return true;
986 case glslang::EOpParameters:
987 // Parameters will have been consumed by EOpFunction processing, but not
988 // the body, so we still visited the function node's children, making this
989 // child redundant.
990 return false;
991 case glslang::EOpFunctionCall:
992 {
993 if (node->isUserDefined())
994 result = handleUserFunctionCall(node);
John Kessenich55e7d112015-11-15 21:33:39 -0700995 assert(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600996 builder.clearAccessChain();
997 builder.setAccessChainRValue(result);
998
999 return false;
1000 }
1001 case glslang::EOpConstructMat2x2:
1002 case glslang::EOpConstructMat2x3:
1003 case glslang::EOpConstructMat2x4:
1004 case glslang::EOpConstructMat3x2:
1005 case glslang::EOpConstructMat3x3:
1006 case glslang::EOpConstructMat3x4:
1007 case glslang::EOpConstructMat4x2:
1008 case glslang::EOpConstructMat4x3:
1009 case glslang::EOpConstructMat4x4:
1010 case glslang::EOpConstructDMat2x2:
1011 case glslang::EOpConstructDMat2x3:
1012 case glslang::EOpConstructDMat2x4:
1013 case glslang::EOpConstructDMat3x2:
1014 case glslang::EOpConstructDMat3x3:
1015 case glslang::EOpConstructDMat3x4:
1016 case glslang::EOpConstructDMat4x2:
1017 case glslang::EOpConstructDMat4x3:
1018 case glslang::EOpConstructDMat4x4:
1019 isMatrix = true;
1020 // fall through
1021 case glslang::EOpConstructFloat:
1022 case glslang::EOpConstructVec2:
1023 case glslang::EOpConstructVec3:
1024 case glslang::EOpConstructVec4:
1025 case glslang::EOpConstructDouble:
1026 case glslang::EOpConstructDVec2:
1027 case glslang::EOpConstructDVec3:
1028 case glslang::EOpConstructDVec4:
1029 case glslang::EOpConstructBool:
1030 case glslang::EOpConstructBVec2:
1031 case glslang::EOpConstructBVec3:
1032 case glslang::EOpConstructBVec4:
1033 case glslang::EOpConstructInt:
1034 case glslang::EOpConstructIVec2:
1035 case glslang::EOpConstructIVec3:
1036 case glslang::EOpConstructIVec4:
1037 case glslang::EOpConstructUint:
1038 case glslang::EOpConstructUVec2:
1039 case glslang::EOpConstructUVec3:
1040 case glslang::EOpConstructUVec4:
1041 case glslang::EOpConstructStruct:
1042 {
1043 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001044 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001045 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1046 spv::Id constructed;
1047 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1048 std::vector<spv::Id> constituents;
1049 for (int c = 0; c < (int)arguments.size(); ++c)
1050 constituents.push_back(arguments[c]);
1051 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001052 } else if (isMatrix)
1053 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1054 else
1055 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001056
1057 builder.clearAccessChain();
1058 builder.setAccessChainRValue(constructed);
1059
1060 return false;
1061 }
1062
1063 // These six are component-wise compares with component-wise results.
1064 // Forward on to createBinaryOperation(), requesting a vector result.
1065 case glslang::EOpLessThan:
1066 case glslang::EOpGreaterThan:
1067 case glslang::EOpLessThanEqual:
1068 case glslang::EOpGreaterThanEqual:
1069 case glslang::EOpVectorEqual:
1070 case glslang::EOpVectorNotEqual:
1071 {
1072 // Map the operation to a binary
1073 binOp = node->getOp();
1074 reduceComparison = false;
1075 switch (node->getOp()) {
1076 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1077 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1078 default: binOp = node->getOp(); break;
1079 }
1080
1081 break;
1082 }
1083 case glslang::EOpMul:
1084 // compontent-wise matrix multiply
1085 binOp = glslang::EOpMul;
1086 break;
1087 case glslang::EOpOuterProduct:
1088 // two vectors multiplied to make a matrix
1089 binOp = glslang::EOpOuterProduct;
1090 break;
1091 case glslang::EOpDot:
1092 {
1093 // for scalar dot product, use multiply
1094 glslang::TIntermSequence& glslangOperands = node->getSequence();
1095 if (! glslangOperands[0]->getAsTyped()->isVector())
1096 binOp = glslang::EOpMul;
1097 break;
1098 }
1099 case glslang::EOpMod:
1100 // when an aggregate, this is the floating-point mod built-in function,
1101 // which can be emitted by the one in createBinaryOperation()
1102 binOp = glslang::EOpMod;
1103 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001104 case glslang::EOpEmitVertex:
1105 case glslang::EOpEndPrimitive:
1106 case glslang::EOpBarrier:
1107 case glslang::EOpMemoryBarrier:
1108 case glslang::EOpMemoryBarrierAtomicCounter:
1109 case glslang::EOpMemoryBarrierBuffer:
1110 case glslang::EOpMemoryBarrierImage:
1111 case glslang::EOpMemoryBarrierShared:
1112 case glslang::EOpGroupMemoryBarrier:
1113 noReturnValue = true;
1114 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1115 break;
1116
John Kessenich426394d2015-07-23 10:22:48 -06001117 case glslang::EOpAtomicAdd:
1118 case glslang::EOpAtomicMin:
1119 case glslang::EOpAtomicMax:
1120 case glslang::EOpAtomicAnd:
1121 case glslang::EOpAtomicOr:
1122 case glslang::EOpAtomicXor:
1123 case glslang::EOpAtomicExchange:
1124 case glslang::EOpAtomicCompSwap:
1125 atomic = true;
1126 break;
1127
John Kessenich140f3df2015-06-26 16:58:36 -06001128 default:
1129 break;
1130 }
1131
1132 //
1133 // See if it maps to a regular operation.
1134 //
John Kessenich140f3df2015-06-26 16:58:36 -06001135 if (binOp != glslang::EOpNull) {
1136 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1137 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1138 assert(left && right);
1139
1140 builder.clearAccessChain();
1141 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001142 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001143
1144 builder.clearAccessChain();
1145 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001146 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001147
1148 result = createBinaryOperation(binOp, precision,
1149 convertGlslangToSpvType(node->getType()), leftId, rightId,
1150 left->getType().getBasicType(), reduceComparison);
1151
1152 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001153 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001154 builder.clearAccessChain();
1155 builder.setAccessChainRValue(result);
1156
1157 return false;
1158 }
1159
John Kessenich426394d2015-07-23 10:22:48 -06001160 //
1161 // Create the list of operands.
1162 //
John Kessenich140f3df2015-06-26 16:58:36 -06001163 glslang::TIntermSequence& glslangOperands = node->getSequence();
1164 std::vector<spv::Id> operands;
1165 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1166 builder.clearAccessChain();
1167 glslangOperands[arg]->traverse(this);
1168
1169 // special case l-value operands; there are just a few
1170 bool lvalue = false;
1171 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001172 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001173 case glslang::EOpModf:
1174 if (arg == 1)
1175 lvalue = true;
1176 break;
Rex Xud4782c12015-09-06 16:30:11 +08001177 case glslang::EOpAtomicAdd:
1178 case glslang::EOpAtomicMin:
1179 case glslang::EOpAtomicMax:
1180 case glslang::EOpAtomicAnd:
1181 case glslang::EOpAtomicOr:
1182 case glslang::EOpAtomicXor:
1183 case glslang::EOpAtomicExchange:
1184 case glslang::EOpAtomicCompSwap:
1185 if (arg == 0)
1186 lvalue = true;
1187 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001188 case glslang::EOpAddCarry:
1189 case glslang::EOpSubBorrow:
1190 if (arg == 2)
1191 lvalue = true;
1192 break;
1193 case glslang::EOpUMulExtended:
1194 case glslang::EOpIMulExtended:
1195 if (arg >= 2)
1196 lvalue = true;
1197 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001198 default:
1199 break;
1200 }
1201 if (lvalue)
1202 operands.push_back(builder.accessChainGetLValue());
1203 else
John Kessenichfa668da2015-09-13 14:46:30 -06001204 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001205 }
John Kessenich426394d2015-07-23 10:22:48 -06001206
1207 if (atomic) {
1208 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001209 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001210 } else {
1211 // Pass through to generic operations.
1212 switch (glslangOperands.size()) {
1213 case 0:
1214 result = createNoArgOperation(node->getOp());
1215 break;
1216 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001217 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001218 break;
1219 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001220 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001221 break;
1222 }
John Kessenich140f3df2015-06-26 16:58:36 -06001223 }
1224
1225 if (noReturnValue)
1226 return false;
1227
1228 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001229 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich140f3df2015-06-26 16:58:36 -06001230 return true;
1231 } else {
1232 builder.clearAccessChain();
1233 builder.setAccessChainRValue(result);
1234 return false;
1235 }
1236}
1237
1238bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1239{
1240 // This path handles both if-then-else and ?:
1241 // The if-then-else has a node type of void, while
1242 // ?: has a non-void node type
1243 spv::Id result = 0;
1244 if (node->getBasicType() != glslang::EbtVoid) {
1245 // don't handle this as just on-the-fly temporaries, because there will be two names
1246 // and better to leave SSA to later passes
1247 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1248 }
1249
1250 // emit the condition before doing anything with selection
1251 node->getCondition()->traverse(this);
1252
1253 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001254 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001255
1256 if (node->getTrueBlock()) {
1257 // emit the "then" statement
1258 node->getTrueBlock()->traverse(this);
1259 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001260 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001261 }
1262
1263 if (node->getFalseBlock()) {
1264 ifBuilder.makeBeginElse();
1265 // emit the "else" statement
1266 node->getFalseBlock()->traverse(this);
1267 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001268 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001269 }
1270
1271 ifBuilder.makeEndIf();
1272
1273 if (result) {
1274 // GLSL only has r-values as the result of a :?, but
1275 // if we have an l-value, that can be more efficient if it will
1276 // become the base of a complex r-value expression, because the
1277 // next layer copies r-values into memory to use the access-chain mechanism
1278 builder.clearAccessChain();
1279 builder.setAccessChainLValue(result);
1280 }
1281
1282 return false;
1283}
1284
1285bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1286{
1287 // emit and get the condition before doing anything with switch
1288 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001289 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001290
1291 // browse the children to sort out code segments
1292 int defaultSegment = -1;
1293 std::vector<TIntermNode*> codeSegments;
1294 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1295 std::vector<int> caseValues;
1296 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1297 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1298 TIntermNode* child = *c;
1299 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001300 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001301 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001302 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001303 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1304 } else
1305 codeSegments.push_back(child);
1306 }
1307
1308 // handle the case where the last code segment is missing, due to no code
1309 // statements between the last case and the end of the switch statement
1310 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1311 (int)codeSegments.size() == defaultSegment)
1312 codeSegments.push_back(nullptr);
1313
1314 // make the switch statement
1315 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001316 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001317
1318 // emit all the code in the segments
1319 breakForLoop.push(false);
1320 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1321 builder.nextSwitchSegment(segmentBlocks, s);
1322 if (codeSegments[s])
1323 codeSegments[s]->traverse(this);
1324 else
1325 builder.addSwitchBreak();
1326 }
1327 breakForLoop.pop();
1328
1329 builder.endSwitch(segmentBlocks);
1330
1331 return false;
1332}
1333
1334void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1335{
1336 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001337 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001338
1339 builder.clearAccessChain();
1340 builder.setAccessChainRValue(constant);
1341}
1342
1343bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1344{
1345 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1346 loopTerminal.push(node->getTerminal());
1347
David Netoc22f37c2015-07-15 16:21:26 -04001348 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001349
1350 if (node->getTest()) {
1351 node->getTest()->traverse(this);
1352 // the AST only contained the test computation, not the branch, we have to add it
John Kessenichfa668da2015-09-13 14:46:30 -06001353 spv::Id condition = builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001354 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001355 } else {
1356 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001357 }
1358
David Netoc22f37c2015-07-15 16:21:26 -04001359 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001360 breakForLoop.push(true);
1361 node->getBody()->traverse(this);
1362 breakForLoop.pop();
1363 }
1364
1365 if (loopTerminal.top())
1366 loopTerminal.top()->traverse(this);
1367
1368 builder.closeLoop();
1369
1370 loopTerminal.pop();
1371
1372 return false;
1373}
1374
1375bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1376{
1377 if (node->getExpression())
1378 node->getExpression()->traverse(this);
1379
1380 switch (node->getFlowOp()) {
1381 case glslang::EOpKill:
1382 builder.makeDiscard();
1383 break;
1384 case glslang::EOpBreak:
1385 if (breakForLoop.top())
1386 builder.createLoopExit();
1387 else
1388 builder.addSwitchBreak();
1389 break;
1390 case glslang::EOpContinue:
1391 if (loopTerminal.top())
1392 loopTerminal.top()->traverse(this);
1393 builder.createLoopContinue();
1394 break;
1395 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001396 if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001397 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001398 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001399 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001400
1401 builder.clearAccessChain();
1402 break;
1403
1404 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001405 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001406 break;
1407 }
1408
1409 return false;
1410}
1411
1412spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1413{
1414 // First, steer off constants, which are not SPIR-V variables, but
1415 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001416 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001417 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001418 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001419 }
1420
1421 // Now, handle actual variables
1422 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1423 spv::Id spvType = convertGlslangToSpvType(node->getType());
1424
1425 const char* name = node->getName().c_str();
1426 if (glslang::IsAnonymous(name))
1427 name = "";
1428
1429 return builder.createVariable(storageClass, spvType, name);
1430}
1431
1432// Return type Id of the sampled type.
1433spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1434{
1435 switch (sampler.type) {
1436 case glslang::EbtFloat: return builder.makeFloatType(32);
1437 case glslang::EbtInt: return builder.makeIntType(32);
1438 case glslang::EbtUint: return builder.makeUintType(32);
1439 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001440 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001441 return builder.makeFloatType(32);
1442 }
1443}
1444
John Kessenich31ed4832015-09-09 17:51:38 -06001445// Convert from a glslang type to an SPV type, by calling into
1446// recursive version of this function.
John Kessenich140f3df2015-06-26 16:58:36 -06001447spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1448{
John Kessenich31ed4832015-09-09 17:51:38 -06001449 return convertGlslangToSpvType(type, requiresExplicitLayout(type));
1450}
1451
1452// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1453// explicitLayout can be kept the same throughout the heirarchical recursive walk.
1454spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout)
1455{
John Kessenich140f3df2015-06-26 16:58:36 -06001456 spv::Id spvType = 0;
1457
1458 switch (type.getBasicType()) {
1459 case glslang::EbtVoid:
1460 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001461 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001462 break;
1463 case glslang::EbtFloat:
1464 spvType = builder.makeFloatType(32);
1465 break;
1466 case glslang::EbtDouble:
1467 spvType = builder.makeFloatType(64);
1468 break;
1469 case glslang::EbtBool:
1470 spvType = builder.makeBoolType();
1471 break;
1472 case glslang::EbtInt:
1473 spvType = builder.makeIntType(32);
1474 break;
1475 case glslang::EbtUint:
1476 spvType = builder.makeUintType(32);
1477 break;
John Kessenich426394d2015-07-23 10:22:48 -06001478 case glslang::EbtAtomicUint:
1479 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1480 spvType = builder.makeUintType(32);
1481 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001482 case glslang::EbtSampler:
1483 {
1484 const glslang::TSampler& sampler = type.getSampler();
John Kessenich55e7d112015-11-15 21:33:39 -07001485 // an image is present, make its type
1486 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1487 sampler.image ? 2 : 1, TranslateImageFormat(type));
1488 if (! sampler.image) {
1489 spvType = builder.makeSampledImageType(spvType);
1490 }
1491 }
John Kessenich140f3df2015-06-26 16:58:36 -06001492 break;
1493 case glslang::EbtStruct:
1494 case glslang::EbtBlock:
1495 {
1496 // If we've seen this struct type, return it
1497 const glslang::TTypeList* glslangStruct = type.getStruct();
1498 std::vector<spv::Id> structFields;
1499 spvType = structMap[glslangStruct];
1500 if (spvType)
1501 break;
1502
1503 // else, we haven't seen it...
1504
1505 // Create a vector of struct types for SPIR-V to consume
1506 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1507 if (type.getBasicType() == glslang::EbtBlock)
1508 memberRemapper[glslangStruct].resize(glslangStruct->size());
1509 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1510 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1511 if (glslangType.hiddenMember()) {
1512 ++memberDelta;
1513 if (type.getBasicType() == glslang::EbtBlock)
1514 memberRemapper[glslangStruct][i] = -1;
1515 } else {
1516 if (type.getBasicType() == glslang::EbtBlock)
1517 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kessenich31ed4832015-09-09 17:51:38 -06001518 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001519 }
1520 }
1521
1522 // Make the SPIR-V type
1523 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
1524 structMap[glslangStruct] = spvType;
1525
1526 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001527 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001528 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1529 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1530 int member = i;
1531 if (type.getBasicType() == glslang::EbtBlock)
1532 member = memberRemapper[glslangStruct][i];
1533 // using -1 above to indicate a hidden member
1534 if (member >= 0) {
1535 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
1536 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType));
1537 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1538 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1539 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1540 if (glslangType.getQualifier().hasLocation())
1541 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1542 if (glslangType.getQualifier().hasComponent())
1543 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1544 if (glslangType.getQualifier().hasXfbOffset())
1545 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenich31ed4832015-09-09 17:51:38 -06001546 else if (explicitLayout) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001547 // figure out what to do with offset, which is accumulating
1548 int nextOffset;
1549 updateMemberOffset(type, glslangType, offset, nextOffset);
1550 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001551 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001552 offset = nextOffset;
1553 }
John Kessenich140f3df2015-06-26 16:58:36 -06001554
John Kessenich31ed4832015-09-09 17:51:38 -06001555 if (glslangType.isMatrix() && explicitLayout) {
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001556 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType));
1557 }
1558
John Kessenich140f3df2015-06-26 16:58:36 -06001559 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001560 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1561 if (builtIn != spv::BadValue)
1562 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001563 }
1564 }
1565
1566 // Decorate the structure
1567 addDecoration(spvType, TranslateLayoutDecoration(type));
1568 addDecoration(spvType, TranslateBlockDecoration(type));
1569 if (type.getQualifier().hasStream())
1570 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1571 if (glslangIntermediate->getXfbMode()) {
1572 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001573 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001574 if (type.getQualifier().hasXfbBuffer())
1575 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1576 }
1577 }
1578 break;
1579 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001580 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001581 break;
1582 }
1583
1584 if (type.isMatrix())
1585 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1586 else {
1587 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1588 if (type.getVectorSize() > 1)
1589 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1590 }
1591
1592 if (type.isArray()) {
John Kessenichc9a80832015-09-12 12:17:44 -06001593 // Do all but the outer dimension
1594 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1595 assert(type.getArraySizes()->getDimSize(dim) > 0);
1596 spvType = builder.makeArrayType(spvType, type.getArraySizes()->getDimSize(dim));
1597 }
John Kessenich31ed4832015-09-09 17:51:38 -06001598
John Kessenichc9a80832015-09-12 12:17:44 -06001599 // Do the outer dimension, which might not be known for a runtime-sized array
1600 if (type.isRuntimeSizedArray()) {
1601 spvType = builder.makeRuntimeArray(spvType);
1602 } else {
1603 assert(type.getOuterArraySize() > 0);
1604 spvType = builder.makeArrayType(spvType, type.getOuterArraySize());
1605 }
1606
John Kessenich55e7d112015-11-15 21:33:39 -07001607 // TODO: explicit layout still needs to be done hierarchically for arrays of arrays, which
John Kessenichc9a80832015-09-12 12:17:44 -06001608 // may still require additional "link time" support from the front-end
1609 // for arrays of arrays
John Kessenich55e7d112015-11-15 21:33:39 -07001610
1611 // We need to decorate array strides for types needing explicit layout,
1612 // except for the very top if it is an array of blocks; that array is
1613 // not laid out in memory in a way needing a stride.
1614 if (explicitLayout && type.getBasicType() != glslang::EbtBlock)
John Kessenich31ed4832015-09-09 17:51:38 -06001615 builder.addDecoration(spvType, spv::DecorationArrayStride, getArrayStride(type));
John Kessenich140f3df2015-06-26 16:58:36 -06001616 }
1617
1618 return spvType;
1619}
1620
John Kessenich31ed4832015-09-09 17:51:38 -06001621bool TGlslangToSpvTraverser::requiresExplicitLayout(const glslang::TType& type) const
1622{
1623 return type.getBasicType() == glslang::EbtBlock &&
1624 type.getQualifier().layoutPacking != glslang::ElpShared &&
1625 type.getQualifier().layoutPacking != glslang::ElpPacked &&
1626 (type.getQualifier().storage == glslang::EvqUniform ||
1627 type.getQualifier().storage == glslang::EvqBuffer);
1628}
1629
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001630// Given an array type, returns the integer stride required for that array
1631int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType)
1632{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001633 int size;
John Kesseniche721f492015-12-06 19:17:49 -07001634 int stride = glslangIntermediate->getBaseAlignment(arrayType, size, arrayType.getQualifier().layoutPacking == glslang::ElpStd140);
1635 if (arrayType.isMatrix()) {
1636 // GLSL strides are set to alignments of the matrix flattened to individual rows/cols,
1637 // but SPV needs an array stride for the whole matrix, not the rows/cols
1638 if (arrayType.getQualifier().layoutMatrix == glslang::ElmRowMajor)
1639 stride *= arrayType.getMatrixRows();
1640 else
1641 stride *= arrayType.getMatrixCols();
1642 }
1643
1644 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001645}
1646
1647// Given a matrix type, returns the integer stride required for that matrix
1648// when used as a member of an interface block
1649int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType)
1650{
1651 int size;
John Kesseniche721f492015-12-06 19:17:49 -07001652 return glslangIntermediate->getBaseAlignment(matrixType, size, matrixType.getQualifier().layoutPacking == glslang::ElpStd140);
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001653}
1654
John Kessenich5e4b1242015-08-06 22:53:06 -06001655// Given a member type of a struct, realign the current offset for it, and compute
1656// the next (not yet aligned) offset for the next member, which will get aligned
1657// on the next call.
1658// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1659// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1660// -1 means a non-forced member offset (no decoration needed).
1661void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset)
1662{
1663 // this will get a positive value when deemed necessary
1664 nextOffset = -1;
1665
1666 bool forceOffset = structType.getQualifier().layoutPacking == glslang::ElpStd140 ||
1667 structType.getQualifier().layoutPacking == glslang::ElpStd430;
1668
1669 // override anything in currentOffset with user-set offset
1670 if (memberType.getQualifier().hasOffset())
1671 currentOffset = memberType.getQualifier().layoutOffset;
1672
1673 // It could be that current linker usage in glslang updated all the layoutOffset,
1674 // in which case the following code does not matter. But, that's not quite right
1675 // once cross-compilation unit GLSL validation is done, as the original user
1676 // settings are needed in layoutOffset, and then the following will come into play.
1677
1678 if (! forceOffset) {
1679 if (! memberType.getQualifier().hasOffset())
1680 currentOffset = -1;
1681
1682 return;
1683 }
1684
1685 // Getting this far means we are forcing offsets
1686 if (currentOffset < 0)
1687 currentOffset = 0;
1688
1689 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1690 // but possibly not yet correctly aligned.
1691
1692 int memberSize;
1693 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, memberType.getQualifier().layoutPacking == glslang::ElpStd140);
1694 glslang::RoundToPow2(currentOffset, memberAlignment);
1695 nextOffset = currentOffset + memberSize;
1696}
1697
John Kessenich140f3df2015-06-26 16:58:36 -06001698bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1699{
1700 return node->getName() == "main(";
1701}
1702
1703// Make all the functions, skeletally, without actually visiting their bodies.
1704void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1705{
1706 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1707 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1708 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1709 continue;
1710
1711 // We're on a user function. Set up the basic interface for the function now,
1712 // so that it's available to call.
1713 // Translating the body will happen later.
1714 //
1715 // Typically (except for a "const in" parameter), an address will be passed to the
1716 // function. What it is an address of varies:
1717 //
1718 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1719 // so that write needs to be to a copy, hence the address of a copy works.
1720 //
1721 // - "const in" parameters can just be the r-value, as no writes need occur.
1722 //
1723 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1724 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1725
1726 std::vector<spv::Id> paramTypes;
1727 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1728
1729 for (int p = 0; p < (int)parameters.size(); ++p) {
1730 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1731 spv::Id typeId = convertGlslangToSpvType(paramType);
1732 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1733 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1734 else
1735 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1736 paramTypes.push_back(typeId);
1737 }
1738
1739 spv::Block* functionBlock;
1740 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1741 paramTypes, &functionBlock);
1742
1743 // Track function to emit/call later
1744 functionMap[glslFunction->getName().c_str()] = function;
1745
1746 // Set the parameter id's
1747 for (int p = 0; p < (int)parameters.size(); ++p) {
1748 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1749 // give a name too
1750 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1751 }
1752 }
1753}
1754
1755// Process all the initializers, while skipping the functions and link objects
1756void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1757{
1758 builder.setBuildPoint(shaderEntry->getLastBlock());
1759 for (int i = 0; i < (int)initializers.size(); ++i) {
1760 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1761 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1762
1763 // We're on a top-level node that's not a function. Treat as an initializer, whose
1764 // code goes into the beginning of main.
1765 initializer->traverse(this);
1766 }
1767 }
1768}
1769
1770// Process all the functions, while skipping initializers.
1771void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1772{
1773 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1774 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1775 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1776 node->traverse(this);
1777 }
1778}
1779
1780void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1781{
1782 // SPIR-V functions should already be in the functionMap from the prepass
1783 // that called makeFunctions().
1784 spv::Function* function = functionMap[node->getName().c_str()];
1785 spv::Block* functionBlock = function->getEntryBlock();
1786 builder.setBuildPoint(functionBlock);
1787}
1788
Rex Xu04db3f52015-09-16 11:44:02 +08001789void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001790{
Rex Xufc618912015-09-09 16:42:49 +08001791 const glslang::TIntermSequence& glslangArguments = node.getSequence();
John Kessenich140f3df2015-06-26 16:58:36 -06001792 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1793 builder.clearAccessChain();
1794 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001795
1796 // Special case l-value operands
1797 bool lvalue = false;
1798 switch (node.getOp()) {
1799 case glslang::EOpImageAtomicAdd:
1800 case glslang::EOpImageAtomicMin:
1801 case glslang::EOpImageAtomicMax:
1802 case glslang::EOpImageAtomicAnd:
1803 case glslang::EOpImageAtomicOr:
1804 case glslang::EOpImageAtomicXor:
1805 case glslang::EOpImageAtomicExchange:
1806 case glslang::EOpImageAtomicCompSwap:
1807 if (i == 0)
1808 lvalue = true;
1809 break;
1810 default:
1811 break;
1812 }
1813
Rex Xu6b86d492015-09-16 17:48:22 +08001814 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08001815 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08001816 else
Rex Xu30f92582015-09-14 10:38:56 +08001817 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001818 }
1819}
1820
John Kessenichfc51d282015-08-19 13:34:18 -06001821void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001822{
John Kessenichfc51d282015-08-19 13:34:18 -06001823 builder.clearAccessChain();
1824 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001825 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06001826}
John Kessenich140f3df2015-06-26 16:58:36 -06001827
John Kessenichfc51d282015-08-19 13:34:18 -06001828spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1829{
Rex Xufc618912015-09-09 16:42:49 +08001830 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06001831 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001832 }
1833
John Kessenichfc51d282015-08-19 13:34:18 -06001834 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06001835 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1836 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1837 std::vector<spv::Id> arguments;
1838 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08001839 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06001840 else
1841 translateArguments(*node->getAsUnaryNode(), arguments);
1842 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1843
1844 spv::Builder::TextureParameters params = { };
1845 params.sampler = arguments[0];
1846
Rex Xu04db3f52015-09-16 11:44:02 +08001847 glslang::TCrackedTextureOp cracked;
1848 node->crackTexture(sampler, cracked);
1849
John Kessenichfc51d282015-08-19 13:34:18 -06001850 // Check for queries
1851 if (cracked.query) {
1852 switch (node->getOp()) {
1853 case glslang::EOpImageQuerySize:
1854 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001855 if (arguments.size() > 1) {
1856 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001857 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001858 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001859 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001860 case glslang::EOpImageQuerySamples:
1861 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001862 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001863 case glslang::EOpTextureQueryLod:
1864 params.coords = arguments[1];
1865 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1866 case glslang::EOpTextureQueryLevels:
1867 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1868 default:
1869 assert(0);
1870 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001871 }
John Kessenich140f3df2015-06-26 16:58:36 -06001872 }
1873
Rex Xufc618912015-09-09 16:42:49 +08001874 // Check for image functions other than queries
1875 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06001876 std::vector<spv::Id> operands;
1877 auto opIt = arguments.begin();
1878 operands.push_back(*(opIt++));
1879 operands.push_back(*(opIt++));
1880 if (node->getOp() == glslang::EOpImageStore)
Rex Xu6b86d492015-09-16 17:48:22 +08001881 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06001882 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07001883 if (sampler.ms) {
1884 operands.push_back(spv::ImageOperandsSampleMask);
1885 operands.push_back(*(opIt++));
1886 }
John Kessenich56bab042015-09-16 10:54:31 -06001887 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
1888 } else if (node->getOp() == glslang::EOpImageStore) {
1889 builder.createNoResultOp(spv::OpImageWrite, operands);
1890 return spv::NoResult;
Rex Xu6b86d492015-09-16 17:48:22 +08001891 } else {
1892 // Process image atomic operations
1893
1894 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
1895 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich56bab042015-09-16 10:54:31 -06001896 operands.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06001897
Rex Xufc618912015-09-09 16:42:49 +08001898 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06001899 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08001900
1901 std::vector<spv::Id> operands;
1902 operands.push_back(pointer);
1903 for (; opIt != arguments.end(); ++opIt)
1904 operands.push_back(*opIt);
1905
Rex Xu04db3f52015-09-16 11:44:02 +08001906 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08001907 }
1908 }
1909
1910 // Check for texture functions other than queries
John Kessenichfc51d282015-08-19 13:34:18 -06001911
Rex Xu71519fe2015-11-11 15:35:47 +08001912 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1913
John Kessenichfc51d282015-08-19 13:34:18 -06001914 // check for bias argument
1915 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08001916 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06001917 int nonBiasArgCount = 2;
1918 if (cracked.offset)
1919 ++nonBiasArgCount;
1920 if (cracked.grad)
1921 nonBiasArgCount += 2;
1922
1923 if ((int)arguments.size() > nonBiasArgCount)
1924 bias = true;
1925 }
1926
John Kessenichfc51d282015-08-19 13:34:18 -06001927 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07001928
John Kessenichfc51d282015-08-19 13:34:18 -06001929 params.coords = arguments[1];
1930 int extraArgs = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001931
1932 // sort out where Dref is coming from
1933 if (sampler.shadow && sampler.dim == glslang::EsdCube && sampler.arrayed)
John Kessenichfc51d282015-08-19 13:34:18 -06001934 params.Dref = arguments[2];
John Kessenich55e7d112015-11-15 21:33:39 -07001935 else if (sampler.shadow && cracked.gather) {
1936 params.Dref = arguments[2];
1937 ++extraArgs;
1938 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06001939 std::vector<spv::Id> indexes;
1940 int comp;
1941 if (cracked.proj)
1942 comp = 3;
1943 else
1944 comp = builder.getNumComponents(params.coords) - 1;
1945 indexes.push_back(comp);
1946 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1947 }
1948 if (cracked.lod) {
1949 params.lod = arguments[2];
1950 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08001951 } else if (sampler.ms) {
1952 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08001953 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06001954 }
1955 if (cracked.grad) {
1956 params.gradX = arguments[2 + extraArgs];
1957 params.gradY = arguments[3 + extraArgs];
1958 extraArgs += 2;
1959 }
John Kessenich55e7d112015-11-15 21:33:39 -07001960 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06001961 params.offset = arguments[2 + extraArgs];
1962 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07001963 } else if (cracked.offsets) {
1964 params.offsets = arguments[2 + extraArgs];
1965 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06001966 }
1967 if (bias) {
1968 params.bias = arguments[2 + extraArgs];
1969 ++extraArgs;
1970 }
John Kessenich55e7d112015-11-15 21:33:39 -07001971 if (cracked.gather && ! sampler.shadow) {
1972 // default component is 0, if missing, otherwise an argument
1973 if (2 + extraArgs < (int)arguments.size()) {
1974 params.comp = arguments[2 + extraArgs];
1975 ++extraArgs;
1976 } else {
1977 params.comp = builder.makeIntConstant(0);
1978 }
1979 }
John Kessenichfc51d282015-08-19 13:34:18 -06001980
John Kessenich55e7d112015-11-15 21:33:39 -07001981 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, cracked.gather, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001982}
1983
1984spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
1985{
1986 // Grab the function's pointer from the previously created function
1987 spv::Function* function = functionMap[node->getName().c_str()];
1988 if (! function)
1989 return 0;
1990
1991 const glslang::TIntermSequence& glslangArgs = node->getSequence();
1992 const glslang::TQualifierList& qualifiers = node->getQualifierList();
1993
1994 // See comments in makeFunctions() for details about the semantics for parameter passing.
1995 //
1996 // These imply we need a four step process:
1997 // 1. Evaluate the arguments
1998 // 2. Allocate and make copies of in, out, and inout arguments
1999 // 3. Make the call
2000 // 4. Copy back the results
2001
2002 // 1. Evaluate the arguments
2003 std::vector<spv::Builder::AccessChain> lValues;
2004 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06002005 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002006 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2007 // build l-value
2008 builder.clearAccessChain();
2009 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06002010 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002011 // keep outputs as l-values, evaluate input-only as r-values
2012 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2013 // save l-value
2014 lValues.push_back(builder.getAccessChain());
2015 } else {
2016 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06002017 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002018 }
2019 }
2020
2021 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2022 // copy the original into that space.
2023 //
2024 // Also, build up the list of actual arguments to pass in for the call
2025 int lValueCount = 0;
2026 int rValueCount = 0;
2027 std::vector<spv::Id> spvArgs;
2028 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2029 spv::Id arg;
2030 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2031 // need space to hold the copy
2032 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2033 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2034 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2035 // need to copy the input into output space
2036 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06002037 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002038 builder.createStore(copy, arg);
2039 }
2040 ++lValueCount;
2041 } else {
2042 arg = rValues[rValueCount];
2043 ++rValueCount;
2044 }
2045 spvArgs.push_back(arg);
2046 }
2047
2048 // 3. Make the call.
2049 spv::Id result = builder.createFunctionCall(function, spvArgs);
2050
2051 // 4. Copy back out an "out" arguments.
2052 lValueCount = 0;
2053 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2054 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2055 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2056 spv::Id copy = builder.createLoad(spvArgs[a]);
2057 builder.setAccessChain(lValues[lValueCount]);
2058 builder.accessChainStore(copy);
2059 }
2060 ++lValueCount;
2061 }
2062 }
2063
2064 return result;
2065}
2066
2067// Translate AST operation to SPV operation, already having SPV-based operands/types.
2068spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2069 spv::Id typeId, spv::Id left, spv::Id right,
2070 glslang::TBasicType typeProxy, bool reduceComparison)
2071{
2072 bool isUnsigned = typeProxy == glslang::EbtUint;
2073 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2074
2075 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002076 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002077 bool comparison = false;
2078
2079 switch (op) {
2080 case glslang::EOpAdd:
2081 case glslang::EOpAddAssign:
2082 if (isFloat)
2083 binOp = spv::OpFAdd;
2084 else
2085 binOp = spv::OpIAdd;
2086 break;
2087 case glslang::EOpSub:
2088 case glslang::EOpSubAssign:
2089 if (isFloat)
2090 binOp = spv::OpFSub;
2091 else
2092 binOp = spv::OpISub;
2093 break;
2094 case glslang::EOpMul:
2095 case glslang::EOpMulAssign:
2096 if (isFloat)
2097 binOp = spv::OpFMul;
2098 else
2099 binOp = spv::OpIMul;
2100 break;
2101 case glslang::EOpVectorTimesScalar:
2102 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002103 if (isFloat) {
2104 if (builder.isVector(right))
2105 std::swap(left, right);
2106 assert(builder.isScalar(right));
2107 needMatchingVectors = false;
2108 binOp = spv::OpVectorTimesScalar;
2109 } else
2110 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002111 break;
2112 case glslang::EOpVectorTimesMatrix:
2113 case glslang::EOpVectorTimesMatrixAssign:
2114 assert(builder.isVector(left));
2115 assert(builder.isMatrix(right));
2116 binOp = spv::OpVectorTimesMatrix;
2117 break;
2118 case glslang::EOpMatrixTimesVector:
2119 assert(builder.isMatrix(left));
2120 assert(builder.isVector(right));
2121 binOp = spv::OpMatrixTimesVector;
2122 break;
2123 case glslang::EOpMatrixTimesScalar:
2124 case glslang::EOpMatrixTimesScalarAssign:
2125 if (builder.isMatrix(right))
2126 std::swap(left, right);
2127 assert(builder.isScalar(right));
2128 binOp = spv::OpMatrixTimesScalar;
2129 break;
2130 case glslang::EOpMatrixTimesMatrix:
2131 case glslang::EOpMatrixTimesMatrixAssign:
2132 assert(builder.isMatrix(left));
2133 assert(builder.isMatrix(right));
2134 binOp = spv::OpMatrixTimesMatrix;
2135 break;
2136 case glslang::EOpOuterProduct:
2137 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002138 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002139 break;
2140
2141 case glslang::EOpDiv:
2142 case glslang::EOpDivAssign:
2143 if (isFloat)
2144 binOp = spv::OpFDiv;
2145 else if (isUnsigned)
2146 binOp = spv::OpUDiv;
2147 else
2148 binOp = spv::OpSDiv;
2149 break;
2150 case glslang::EOpMod:
2151 case glslang::EOpModAssign:
2152 if (isFloat)
2153 binOp = spv::OpFMod;
2154 else if (isUnsigned)
2155 binOp = spv::OpUMod;
2156 else
2157 binOp = spv::OpSMod;
2158 break;
2159 case glslang::EOpRightShift:
2160 case glslang::EOpRightShiftAssign:
2161 if (isUnsigned)
2162 binOp = spv::OpShiftRightLogical;
2163 else
2164 binOp = spv::OpShiftRightArithmetic;
2165 break;
2166 case glslang::EOpLeftShift:
2167 case glslang::EOpLeftShiftAssign:
2168 binOp = spv::OpShiftLeftLogical;
2169 break;
2170 case glslang::EOpAnd:
2171 case glslang::EOpAndAssign:
2172 binOp = spv::OpBitwiseAnd;
2173 break;
2174 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002175 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002176 binOp = spv::OpLogicalAnd;
2177 break;
2178 case glslang::EOpInclusiveOr:
2179 case glslang::EOpInclusiveOrAssign:
2180 binOp = spv::OpBitwiseOr;
2181 break;
2182 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002183 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002184 binOp = spv::OpLogicalOr;
2185 break;
2186 case glslang::EOpExclusiveOr:
2187 case glslang::EOpExclusiveOrAssign:
2188 binOp = spv::OpBitwiseXor;
2189 break;
2190 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002191 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002192 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002193 break;
2194
2195 case glslang::EOpLessThan:
2196 case glslang::EOpGreaterThan:
2197 case glslang::EOpLessThanEqual:
2198 case glslang::EOpGreaterThanEqual:
2199 case glslang::EOpEqual:
2200 case glslang::EOpNotEqual:
2201 case glslang::EOpVectorEqual:
2202 case glslang::EOpVectorNotEqual:
2203 comparison = true;
2204 break;
2205 default:
2206 break;
2207 }
2208
John Kessenich7c1aa102015-10-15 13:29:11 -06002209 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002210 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002211 assert(comparison == false);
John Kessenich140f3df2015-06-26 16:58:36 -06002212 if (builder.isMatrix(left) || builder.isMatrix(right)) {
2213 switch (binOp) {
2214 case spv::OpMatrixTimesScalar:
2215 case spv::OpVectorTimesMatrix:
2216 case spv::OpMatrixTimesVector:
2217 case spv::OpMatrixTimesMatrix:
2218 break;
2219 case spv::OpFDiv:
2220 // turn it into a multiply...
2221 assert(builder.isMatrix(left) && builder.isScalar(right));
2222 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2223 binOp = spv::OpFMul;
2224 break;
2225 default:
2226 spv::MissingFunctionality("binary operation on matrix");
2227 break;
2228 }
2229
2230 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2231 builder.setPrecision(id, precision);
2232
2233 return id;
2234 }
2235
2236 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002237 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002238 builder.promoteScalar(precision, left, right);
2239
2240 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2241 builder.setPrecision(id, precision);
2242
2243 return id;
2244 }
2245
2246 if (! comparison)
2247 return 0;
2248
John Kessenich7c1aa102015-10-15 13:29:11 -06002249 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002250
2251 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2252 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2253
2254 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
2255 }
2256
2257 switch (op) {
2258 case glslang::EOpLessThan:
2259 if (isFloat)
2260 binOp = spv::OpFOrdLessThan;
2261 else if (isUnsigned)
2262 binOp = spv::OpULessThan;
2263 else
2264 binOp = spv::OpSLessThan;
2265 break;
2266 case glslang::EOpGreaterThan:
2267 if (isFloat)
2268 binOp = spv::OpFOrdGreaterThan;
2269 else if (isUnsigned)
2270 binOp = spv::OpUGreaterThan;
2271 else
2272 binOp = spv::OpSGreaterThan;
2273 break;
2274 case glslang::EOpLessThanEqual:
2275 if (isFloat)
2276 binOp = spv::OpFOrdLessThanEqual;
2277 else if (isUnsigned)
2278 binOp = spv::OpULessThanEqual;
2279 else
2280 binOp = spv::OpSLessThanEqual;
2281 break;
2282 case glslang::EOpGreaterThanEqual:
2283 if (isFloat)
2284 binOp = spv::OpFOrdGreaterThanEqual;
2285 else if (isUnsigned)
2286 binOp = spv::OpUGreaterThanEqual;
2287 else
2288 binOp = spv::OpSGreaterThanEqual;
2289 break;
2290 case glslang::EOpEqual:
2291 case glslang::EOpVectorEqual:
2292 if (isFloat)
2293 binOp = spv::OpFOrdEqual;
2294 else
2295 binOp = spv::OpIEqual;
2296 break;
2297 case glslang::EOpNotEqual:
2298 case glslang::EOpVectorNotEqual:
2299 if (isFloat)
2300 binOp = spv::OpFOrdNotEqual;
2301 else
2302 binOp = spv::OpINotEqual;
2303 break;
2304 default:
2305 break;
2306 }
2307
2308 if (binOp != spv::OpNop) {
2309 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2310 builder.setPrecision(id, precision);
2311
2312 return id;
2313 }
2314
2315 return 0;
2316}
2317
Rex Xu04db3f52015-09-16 11:44:02 +08002318spv::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 -06002319{
2320 spv::Op unaryOp = spv::OpNop;
2321 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002322 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002323 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002324
2325 switch (op) {
2326 case glslang::EOpNegative:
2327 if (isFloat)
2328 unaryOp = spv::OpFNegate;
2329 else
2330 unaryOp = spv::OpSNegate;
2331 break;
2332
2333 case glslang::EOpLogicalNot:
2334 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002335 unaryOp = spv::OpLogicalNot;
2336 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002337 case glslang::EOpBitwiseNot:
2338 unaryOp = spv::OpNot;
2339 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002340
John Kessenich140f3df2015-06-26 16:58:36 -06002341 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002342 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002343 break;
2344 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002345 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002346 break;
2347 case glslang::EOpTranspose:
2348 unaryOp = spv::OpTranspose;
2349 break;
2350
2351 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002352 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002353 break;
2354 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002355 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002356 break;
2357 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002358 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002359 break;
2360 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002361 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002362 break;
2363 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002364 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002365 break;
2366 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002367 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002368 break;
2369 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002370 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002371 break;
2372 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002373 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002374 break;
2375
2376 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002377 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002378 break;
2379 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002380 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002381 break;
2382 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002383 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002384 break;
2385 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002386 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002387 break;
2388 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002389 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002390 break;
2391 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002392 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002393 break;
2394
2395 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002396 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002397 break;
2398 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002399 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002400 break;
2401
2402 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002403 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002404 break;
2405 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002406 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002407 break;
2408 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002409 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002410 break;
2411 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002412 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002413 break;
2414 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002415 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002416 break;
2417 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002418 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002419 break;
2420
2421 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002422 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002423 break;
2424 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002425 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002426 break;
2427 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002428 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002429 break;
2430 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002431 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002432 break;
2433 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002434 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002435 break;
2436 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002437 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002438 break;
2439
2440 case glslang::EOpIsNan:
2441 unaryOp = spv::OpIsNan;
2442 break;
2443 case glslang::EOpIsInf:
2444 unaryOp = spv::OpIsInf;
2445 break;
2446
John Kessenich140f3df2015-06-26 16:58:36 -06002447 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002448 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002449 break;
2450 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002451 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002452 break;
2453 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002454 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002455 break;
2456 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002457 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002458 break;
2459 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002460 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002461 break;
2462 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002463 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002464 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002465 case glslang::EOpPackSnorm4x8:
2466 libCall = spv::GLSLstd450PackSnorm4x8;
2467 break;
2468 case glslang::EOpUnpackSnorm4x8:
2469 libCall = spv::GLSLstd450UnpackSnorm4x8;
2470 break;
2471 case glslang::EOpPackUnorm4x8:
2472 libCall = spv::GLSLstd450PackUnorm4x8;
2473 break;
2474 case glslang::EOpUnpackUnorm4x8:
2475 libCall = spv::GLSLstd450UnpackUnorm4x8;
2476 break;
2477 case glslang::EOpPackDouble2x32:
2478 libCall = spv::GLSLstd450PackDouble2x32;
2479 break;
2480 case glslang::EOpUnpackDouble2x32:
2481 libCall = spv::GLSLstd450UnpackDouble2x32;
2482 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002483
2484 case glslang::EOpDPdx:
2485 unaryOp = spv::OpDPdx;
2486 break;
2487 case glslang::EOpDPdy:
2488 unaryOp = spv::OpDPdy;
2489 break;
2490 case glslang::EOpFwidth:
2491 unaryOp = spv::OpFwidth;
2492 break;
2493 case glslang::EOpDPdxFine:
2494 unaryOp = spv::OpDPdxFine;
2495 break;
2496 case glslang::EOpDPdyFine:
2497 unaryOp = spv::OpDPdyFine;
2498 break;
2499 case glslang::EOpFwidthFine:
2500 unaryOp = spv::OpFwidthFine;
2501 break;
2502 case glslang::EOpDPdxCoarse:
2503 unaryOp = spv::OpDPdxCoarse;
2504 break;
2505 case glslang::EOpDPdyCoarse:
2506 unaryOp = spv::OpDPdyCoarse;
2507 break;
2508 case glslang::EOpFwidthCoarse:
2509 unaryOp = spv::OpFwidthCoarse;
2510 break;
2511
2512 case glslang::EOpAny:
2513 unaryOp = spv::OpAny;
2514 break;
2515 case glslang::EOpAll:
2516 unaryOp = spv::OpAll;
2517 break;
2518
2519 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002520 if (isFloat)
2521 libCall = spv::GLSLstd450FAbs;
2522 else
2523 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002524 break;
2525 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002526 if (isFloat)
2527 libCall = spv::GLSLstd450FSign;
2528 else
2529 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002530 break;
2531
John Kessenichfc51d282015-08-19 13:34:18 -06002532 case glslang::EOpAtomicCounterIncrement:
2533 case glslang::EOpAtomicCounterDecrement:
2534 case glslang::EOpAtomicCounter:
2535 {
2536 // Handle all of the atomics in one place, in createAtomicOperation()
2537 std::vector<spv::Id> operands;
2538 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002539 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002540 }
2541
2542 case glslang::EOpImageLoad:
2543 unaryOp = spv::OpImageRead;
2544 break;
2545
2546 case glslang::EOpBitFieldReverse:
2547 unaryOp = spv::OpBitReverse;
2548 break;
2549 case glslang::EOpBitCount:
2550 unaryOp = spv::OpBitCount;
2551 break;
2552 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002553 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002554 break;
2555 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002556 if (isUnsigned)
2557 libCall = spv::GLSLstd450FindUMsb;
2558 else
2559 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002560 break;
2561
John Kessenich140f3df2015-06-26 16:58:36 -06002562 default:
2563 return 0;
2564 }
2565
2566 spv::Id id;
2567 if (libCall >= 0) {
2568 std::vector<spv::Id> args;
2569 args.push_back(operand);
2570 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2571 } else
2572 id = builder.createUnaryOp(unaryOp, typeId, operand);
2573
2574 builder.setPrecision(id, precision);
2575
2576 return id;
2577}
2578
2579spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2580{
2581 spv::Op convOp = spv::OpNop;
2582 spv::Id zero = 0;
2583 spv::Id one = 0;
2584
2585 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2586
2587 switch (op) {
2588 case glslang::EOpConvIntToBool:
2589 case glslang::EOpConvUintToBool:
2590 zero = builder.makeUintConstant(0);
2591 zero = makeSmearedConstant(zero, vectorSize);
2592 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2593
2594 case glslang::EOpConvFloatToBool:
2595 zero = builder.makeFloatConstant(0.0F);
2596 zero = makeSmearedConstant(zero, vectorSize);
2597 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2598
2599 case glslang::EOpConvDoubleToBool:
2600 zero = builder.makeDoubleConstant(0.0);
2601 zero = makeSmearedConstant(zero, vectorSize);
2602 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2603
2604 case glslang::EOpConvBoolToFloat:
2605 convOp = spv::OpSelect;
2606 zero = builder.makeFloatConstant(0.0);
2607 one = builder.makeFloatConstant(1.0);
2608 break;
2609 case glslang::EOpConvBoolToDouble:
2610 convOp = spv::OpSelect;
2611 zero = builder.makeDoubleConstant(0.0);
2612 one = builder.makeDoubleConstant(1.0);
2613 break;
2614 case glslang::EOpConvBoolToInt:
2615 zero = builder.makeIntConstant(0);
2616 one = builder.makeIntConstant(1);
2617 convOp = spv::OpSelect;
2618 break;
2619 case glslang::EOpConvBoolToUint:
2620 zero = builder.makeUintConstant(0);
2621 one = builder.makeUintConstant(1);
2622 convOp = spv::OpSelect;
2623 break;
2624
2625 case glslang::EOpConvIntToFloat:
2626 case glslang::EOpConvIntToDouble:
2627 convOp = spv::OpConvertSToF;
2628 break;
2629
2630 case glslang::EOpConvUintToFloat:
2631 case glslang::EOpConvUintToDouble:
2632 convOp = spv::OpConvertUToF;
2633 break;
2634
2635 case glslang::EOpConvDoubleToFloat:
2636 case glslang::EOpConvFloatToDouble:
2637 convOp = spv::OpFConvert;
2638 break;
2639
2640 case glslang::EOpConvFloatToInt:
2641 case glslang::EOpConvDoubleToInt:
2642 convOp = spv::OpConvertFToS;
2643 break;
2644
2645 case glslang::EOpConvUintToInt:
2646 case glslang::EOpConvIntToUint:
2647 convOp = spv::OpBitcast;
2648 break;
2649
2650 case glslang::EOpConvFloatToUint:
2651 case glslang::EOpConvDoubleToUint:
2652 convOp = spv::OpConvertFToU;
2653 break;
2654 default:
2655 break;
2656 }
2657
2658 spv::Id result = 0;
2659 if (convOp == spv::OpNop)
2660 return result;
2661
2662 if (convOp == spv::OpSelect) {
2663 zero = makeSmearedConstant(zero, vectorSize);
2664 one = makeSmearedConstant(one, vectorSize);
2665 result = builder.createTriOp(convOp, destType, operand, one, zero);
2666 } else
2667 result = builder.createUnaryOp(convOp, destType, operand);
2668
2669 builder.setPrecision(result, precision);
2670
2671 return result;
2672}
2673
2674spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2675{
2676 if (vectorSize == 0)
2677 return constant;
2678
2679 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2680 std::vector<spv::Id> components;
2681 for (int c = 0; c < vectorSize; ++c)
2682 components.push_back(constant);
2683 return builder.makeCompositeConstant(vectorTypeId, components);
2684}
2685
John Kessenich426394d2015-07-23 10:22:48 -06002686// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08002687spv::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 -06002688{
2689 spv::Op opCode = spv::OpNop;
2690
2691 switch (op) {
2692 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08002693 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06002694 opCode = spv::OpAtomicIAdd;
2695 break;
2696 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08002697 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08002698 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002699 break;
2700 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08002701 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08002702 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002703 break;
2704 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08002705 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06002706 opCode = spv::OpAtomicAnd;
2707 break;
2708 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08002709 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06002710 opCode = spv::OpAtomicOr;
2711 break;
2712 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08002713 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06002714 opCode = spv::OpAtomicXor;
2715 break;
2716 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08002717 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06002718 opCode = spv::OpAtomicExchange;
2719 break;
2720 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08002721 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06002722 opCode = spv::OpAtomicCompareExchange;
2723 break;
2724 case glslang::EOpAtomicCounterIncrement:
2725 opCode = spv::OpAtomicIIncrement;
2726 break;
2727 case glslang::EOpAtomicCounterDecrement:
2728 opCode = spv::OpAtomicIDecrement;
2729 break;
2730 case glslang::EOpAtomicCounter:
2731 opCode = spv::OpAtomicLoad;
2732 break;
2733 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002734 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06002735 break;
2736 }
2737
2738 // Sort out the operands
2739 // - mapping from glslang -> SPV
2740 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06002741 // - compare-exchange swaps the value and comparator
2742 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06002743 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2744 auto opIt = operands.begin(); // walk the glslang operands
2745 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08002746 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2747 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
2748 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08002749 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
2750 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08002751 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06002752 spvAtomicOperands.push_back(*(opIt + 1));
2753 spvAtomicOperands.push_back(*opIt);
2754 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08002755 }
John Kessenich426394d2015-07-23 10:22:48 -06002756
John Kessenich3e60a6f2015-09-14 22:45:16 -06002757 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06002758 for (; opIt != operands.end(); ++opIt)
2759 spvAtomicOperands.push_back(*opIt);
2760
2761 return builder.createOp(opCode, typeId, spvAtomicOperands);
2762}
2763
John Kessenich5e4b1242015-08-06 22:53:06 -06002764spv::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 -06002765{
John Kessenich5e4b1242015-08-06 22:53:06 -06002766 bool isUnsigned = typeProxy == glslang::EbtUint;
2767 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2768
John Kessenich140f3df2015-06-26 16:58:36 -06002769 spv::Op opCode = spv::OpNop;
2770 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002771 int consumedOperands = operands.size();
2772 spv::Id typeId0 = 0;
2773 if (consumedOperands > 0)
2774 typeId0 = builder.getTypeId(operands[0]);
2775 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002776
2777 switch (op) {
2778 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002779 if (isFloat)
2780 libCall = spv::GLSLstd450FMin;
2781 else if (isUnsigned)
2782 libCall = spv::GLSLstd450UMin;
2783 else
2784 libCall = spv::GLSLstd450SMin;
John Kessenich140f3df2015-06-26 16:58:36 -06002785 break;
2786 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002787 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002788 break;
2789 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002790 if (isFloat)
2791 libCall = spv::GLSLstd450FMax;
2792 else if (isUnsigned)
2793 libCall = spv::GLSLstd450UMax;
2794 else
2795 libCall = spv::GLSLstd450SMax;
John Kessenich140f3df2015-06-26 16:58:36 -06002796 break;
2797 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002798 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002799 break;
2800 case glslang::EOpDot:
2801 opCode = spv::OpDot;
2802 break;
2803 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002804 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002805 break;
2806
2807 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002808 if (isFloat)
2809 libCall = spv::GLSLstd450FClamp;
2810 else if (isUnsigned)
2811 libCall = spv::GLSLstd450UClamp;
2812 else
2813 libCall = spv::GLSLstd450SClamp;
John Kessenich140f3df2015-06-26 16:58:36 -06002814 break;
2815 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07002816 if (isFloat)
2817 libCall = spv::GLSLstd450FMix;
2818 else
2819 libCall = spv::GLSLstd450IMix;
John Kessenich140f3df2015-06-26 16:58:36 -06002820 break;
2821 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002822 libCall = spv::GLSLstd450Step;
John Kessenich140f3df2015-06-26 16:58:36 -06002823 break;
2824 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002825 libCall = spv::GLSLstd450SmoothStep;
John Kessenich140f3df2015-06-26 16:58:36 -06002826 break;
2827
2828 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002829 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002830 break;
2831 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002832 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002833 break;
2834 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002835 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002836 break;
2837 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002838 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002839 break;
2840 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002841 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002842 break;
John Kessenich426394d2015-07-23 10:22:48 -06002843
John Kessenich55e7d112015-11-15 21:33:39 -07002844 case glslang::EOpAddCarry:
2845 opCode = spv::OpIAddCarry;
2846 typeId = builder.makeStructResultType(typeId0, typeId0);
2847 consumedOperands = 2;
2848 break;
2849 case glslang::EOpSubBorrow:
2850 opCode = spv::OpISubBorrow;
2851 typeId = builder.makeStructResultType(typeId0, typeId0);
2852 consumedOperands = 2;
2853 break;
2854 case glslang::EOpUMulExtended:
2855 opCode = spv::OpUMulExtended;
2856 typeId = builder.makeStructResultType(typeId0, typeId0);
2857 consumedOperands = 2;
2858 break;
2859 case glslang::EOpIMulExtended:
2860 opCode = spv::OpSMulExtended;
2861 typeId = builder.makeStructResultType(typeId0, typeId0);
2862 consumedOperands = 2;
2863 break;
2864 case glslang::EOpBitfieldExtract:
2865 if (isUnsigned)
2866 opCode = spv::OpBitFieldUExtract;
2867 else
2868 opCode = spv::OpBitFieldSExtract;
2869 break;
2870 case glslang::EOpBitfieldInsert:
2871 opCode = spv::OpBitFieldInsert;
2872 break;
2873
2874 case glslang::EOpFma:
2875 libCall = spv::GLSLstd450Fma;
2876 break;
2877 case glslang::EOpFrexp:
2878 libCall = spv::GLSLstd450FrexpStruct;
2879 if (builder.getNumComponents(operands[0]) == 1)
2880 frexpIntType = builder.makeIntegerType(32, true);
2881 else
2882 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
2883 typeId = builder.makeStructResultType(typeId0, frexpIntType);
2884 consumedOperands = 1;
2885 break;
2886 case glslang::EOpLdexp:
2887 libCall = spv::GLSLstd450Ldexp;
2888 break;
2889
John Kessenich140f3df2015-06-26 16:58:36 -06002890 default:
2891 return 0;
2892 }
2893
2894 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07002895 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05002896 // Use an extended instruction from the standard library.
2897 // Construct the call arguments, without modifying the original operands vector.
2898 // We might need the remaining arguments, e.g. in the EOpFrexp case.
2899 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
2900 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07002901 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07002902 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06002903 case 0:
2904 // should all be handled by visitAggregate and createNoArgOperation
2905 assert(0);
2906 return 0;
2907 case 1:
2908 // should all be handled by createUnaryOperation
2909 assert(0);
2910 return 0;
2911 case 2:
2912 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
2913 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002914 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002915 // anything 3 or over doesn't have l-value operands, so all should be consumed
2916 assert(consumedOperands == operands.size());
2917 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06002918 break;
2919 }
2920 }
2921
John Kessenich55e7d112015-11-15 21:33:39 -07002922 // Decode the return types that were structures
2923 switch (op) {
2924 case glslang::EOpAddCarry:
2925 case glslang::EOpSubBorrow:
2926 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
2927 id = builder.createCompositeExtract(id, typeId0, 0);
2928 break;
2929 case glslang::EOpUMulExtended:
2930 case glslang::EOpIMulExtended:
2931 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
2932 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
2933 break;
2934 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05002935 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07002936 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
2937 id = builder.createCompositeExtract(id, typeId0, 0);
2938 break;
2939 default:
2940 break;
2941 }
2942
John Kessenich140f3df2015-06-26 16:58:36 -06002943 builder.setPrecision(id, precision);
2944
2945 return id;
2946}
2947
2948// Intrinsics with no arguments, no return value, and no precision.
2949spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
2950{
2951 // TODO: get the barrier operands correct
2952
2953 switch (op) {
2954 case glslang::EOpEmitVertex:
2955 builder.createNoResultOp(spv::OpEmitVertex);
2956 return 0;
2957 case glslang::EOpEndPrimitive:
2958 builder.createNoResultOp(spv::OpEndPrimitive);
2959 return 0;
2960 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002961 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
2962 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06002963 return 0;
2964 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002965 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06002966 return 0;
2967 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06002968 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002969 return 0;
2970 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06002971 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002972 return 0;
2973 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06002974 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002975 return 0;
2976 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07002977 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002978 return 0;
2979 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07002980 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002981 return 0;
2982 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002983 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06002984 return 0;
2985 }
2986}
2987
2988spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
2989{
John Kessenich2f273362015-07-18 22:34:27 -06002990 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06002991 spv::Id id;
2992 if (symbolValues.end() != iter) {
2993 id = iter->second;
2994 return id;
2995 }
2996
2997 // it was not found, create it
2998 id = createSpvVariable(symbol);
2999 symbolValues[symbol->getId()] = id;
3000
3001 if (! symbol->getType().isStruct()) {
3002 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
3003 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
3004 if (symbol->getQualifier().hasLocation())
3005 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3006 if (symbol->getQualifier().hasIndex())
3007 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3008 if (symbol->getQualifier().hasComponent())
3009 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3010 if (glslangIntermediate->getXfbMode()) {
3011 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003012 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003013 if (symbol->getQualifier().hasXfbBuffer())
3014 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3015 if (symbol->getQualifier().hasXfbOffset())
3016 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3017 }
3018 }
3019
3020 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
3021 if (symbol->getQualifier().hasStream())
3022 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
3023 if (symbol->getQualifier().hasSet())
3024 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3025 if (symbol->getQualifier().hasBinding())
3026 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3027 if (glslangIntermediate->getXfbMode()) {
3028 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003029 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003030 if (symbol->getQualifier().hasXfbBuffer())
3031 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3032 }
3033
3034 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003035 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003036 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06003037 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003038
John Kessenich140f3df2015-06-26 16:58:36 -06003039 return id;
3040}
3041
John Kessenich55e7d112015-11-15 21:33:39 -07003042// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003043void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3044{
3045 if (dec != spv::BadValue)
3046 builder.addDecoration(id, dec);
3047}
3048
John Kessenich55e7d112015-11-15 21:33:39 -07003049// If 'dec' is valid, add a one-operand decoration to an object
3050void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3051{
3052 if (dec != spv::BadValue)
3053 builder.addDecoration(id, dec, value);
3054}
3055
3056// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003057void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3058{
3059 if (dec != spv::BadValue)
3060 builder.addMemberDecoration(id, (unsigned)member, dec);
3061}
3062
John Kessenich55e7d112015-11-15 21:33:39 -07003063// Make a full tree of instructions to build a SPIR-V specialization constant,
3064// or regularly constant if possible.
3065//
3066// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3067//
3068// Recursively walk the nodes. The nodes form a tree whose leaves are
3069// regular constants, which themselves are trees that createSpvConstant()
3070// recursively walks. So, this function walks the "top" of the tree:
3071// - emit specialization constant-building instructions for specConstant
3072// - when running into a non-spec-constant, switch to createSpvConstant()
3073spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3074{
3075 assert(node.getQualifier().storage == glslang::EvqConst);
3076
3077 // hand off to the non-spec-constant path
3078 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3079 int nextConst = 0;
3080 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3081}
3082
John Kessenich140f3df2015-06-26 16:58:36 -06003083// Use 'consts' as the flattened glslang source of scalar constants to recursively
3084// build the aggregate SPIR-V constant.
3085//
3086// If there are not enough elements present in 'consts', 0 will be substituted;
3087// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3088//
John Kessenich55e7d112015-11-15 21:33:39 -07003089spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003090{
3091 // vector of constants for SPIR-V
3092 std::vector<spv::Id> spvConsts;
3093
3094 // Type is used for struct and array constants
3095 spv::Id typeId = convertGlslangToSpvType(glslangType);
3096
3097 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003098 glslang::TType elementType(glslangType, 0);
3099 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003100 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003101 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003102 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003103 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003104 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003105 } else if (glslangType.getStruct()) {
3106 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3107 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003108 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003109 } else if (glslangType.isVector()) {
3110 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3111 bool zero = nextConst >= consts.size();
3112 switch (glslangType.getBasicType()) {
3113 case glslang::EbtInt:
3114 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3115 break;
3116 case glslang::EbtUint:
3117 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3118 break;
3119 case glslang::EbtFloat:
3120 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3121 break;
3122 case glslang::EbtDouble:
3123 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3124 break;
3125 case glslang::EbtBool:
3126 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3127 break;
3128 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003129 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003130 break;
3131 }
3132 ++nextConst;
3133 }
3134 } else {
3135 // we have a non-aggregate (scalar) constant
3136 bool zero = nextConst >= consts.size();
3137 spv::Id scalar = 0;
3138 switch (glslangType.getBasicType()) {
3139 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003140 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003141 break;
3142 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003143 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003144 break;
3145 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003146 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003147 break;
3148 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003149 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003150 break;
3151 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003152 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003153 break;
3154 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003155 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003156 break;
3157 }
3158 ++nextConst;
3159 return scalar;
3160 }
3161
3162 return builder.makeCompositeConstant(typeId, spvConsts);
3163}
3164
John Kessenich7c1aa102015-10-15 13:29:11 -06003165// Return true if the node is a constant or symbol whose reading has no
3166// non-trivial observable cost or effect.
3167bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3168{
3169 // don't know what this is
3170 if (node == nullptr)
3171 return false;
3172
3173 // a constant is safe
3174 if (node->getAsConstantUnion() != nullptr)
3175 return true;
3176
3177 // not a symbol means non-trivial
3178 if (node->getAsSymbolNode() == nullptr)
3179 return false;
3180
3181 // a symbol, depends on what's being read
3182 switch (node->getType().getQualifier().storage) {
3183 case glslang::EvqTemporary:
3184 case glslang::EvqGlobal:
3185 case glslang::EvqIn:
3186 case glslang::EvqInOut:
3187 case glslang::EvqConst:
3188 case glslang::EvqConstReadOnly:
3189 case glslang::EvqUniform:
3190 return true;
3191 default:
3192 return false;
3193 }
3194}
3195
3196// A node is trivial if it is a single operation with no side effects.
3197// Error on the side of saying non-trivial.
3198// Return true if trivial.
3199bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3200{
3201 if (node == nullptr)
3202 return false;
3203
3204 // symbols and constants are trivial
3205 if (isTrivialLeaf(node))
3206 return true;
3207
3208 // otherwise, it needs to be a simple operation or one or two leaf nodes
3209
3210 // not a simple operation
3211 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3212 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3213 if (binaryNode == nullptr && unaryNode == nullptr)
3214 return false;
3215
3216 // not on leaf nodes
3217 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3218 return false;
3219
3220 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3221 return false;
3222 }
3223
3224 switch (node->getAsOperator()->getOp()) {
3225 case glslang::EOpLogicalNot:
3226 case glslang::EOpConvIntToBool:
3227 case glslang::EOpConvUintToBool:
3228 case glslang::EOpConvFloatToBool:
3229 case glslang::EOpConvDoubleToBool:
3230 case glslang::EOpEqual:
3231 case glslang::EOpNotEqual:
3232 case glslang::EOpLessThan:
3233 case glslang::EOpGreaterThan:
3234 case glslang::EOpLessThanEqual:
3235 case glslang::EOpGreaterThanEqual:
3236 case glslang::EOpIndexDirect:
3237 case glslang::EOpIndexDirectStruct:
3238 case glslang::EOpLogicalXor:
3239 case glslang::EOpAny:
3240 case glslang::EOpAll:
3241 return true;
3242 default:
3243 return false;
3244 }
3245}
3246
3247// Emit short-circuiting code, where 'right' is never evaluated unless
3248// the left side is true (for &&) or false (for ||).
3249spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3250{
3251 spv::Id boolTypeId = builder.makeBoolType();
3252
3253 // emit left operand
3254 builder.clearAccessChain();
3255 left.traverse(this);
3256 spv::Id leftId = builder.accessChainLoad(boolTypeId);
3257
3258 // Operands to accumulate OpPhi operands
3259 std::vector<spv::Id> phiOperands;
3260 // accumulate left operand's phi information
3261 phiOperands.push_back(leftId);
3262 phiOperands.push_back(builder.getBuildPoint()->getId());
3263
3264 // Make the two kinds of operation symmetric with a "!"
3265 // || => emit "if (! left) result = right"
3266 // && => emit "if ( left) result = right"
3267 //
3268 // TODO: this runtime "not" for || could be avoided by adding functionality
3269 // to 'builder' to have an "else" without an "then"
3270 if (op == glslang::EOpLogicalOr)
3271 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3272
3273 // make an "if" based on the left value
3274 spv::Builder::If ifBuilder(leftId, builder);
3275
3276 // emit right operand as the "then" part of the "if"
3277 builder.clearAccessChain();
3278 right.traverse(this);
3279 spv::Id rightId = builder.accessChainLoad(boolTypeId);
3280
3281 // accumulate left operand's phi information
3282 phiOperands.push_back(rightId);
3283 phiOperands.push_back(builder.getBuildPoint()->getId());
3284
3285 // finish the "if"
3286 ifBuilder.makeEndIf();
3287
3288 // phi together the two results
3289 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3290}
3291
John Kessenich140f3df2015-06-26 16:58:36 -06003292}; // end anonymous namespace
3293
3294namespace glslang {
3295
John Kessenich68d78fd2015-07-12 19:28:10 -06003296void GetSpirvVersion(std::string& version)
3297{
John Kessenich9e55f632015-07-15 10:03:39 -06003298 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003299 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003300 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003301 version = buf;
3302}
3303
John Kessenich140f3df2015-06-26 16:58:36 -06003304// Write SPIR-V out to a binary file
3305void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3306{
3307 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003308 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003309 for (int i = 0; i < (int)spirv.size(); ++i) {
3310 unsigned int word = spirv[i];
3311 out.write((const char*)&word, 4);
3312 }
3313 out.close();
3314}
3315
3316//
3317// Set up the glslang traversal
3318//
3319void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3320{
3321 TIntermNode* root = intermediate.getTreeRoot();
3322
3323 if (root == 0)
3324 return;
3325
3326 glslang::GetThreadPoolAllocator().push();
3327
3328 TGlslangToSpvTraverser it(&intermediate);
3329
3330 root->traverse(&it);
3331
3332 it.dumpSpv(spirv);
3333
3334 glslang::GetThreadPoolAllocator().pop();
3335}
3336
3337}; // end namespace glslang