blob: 00369d21845457c65833c0b54491d7975131c520 [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
John Kessenich140f3df2015-06-26 16:58:36 -0600145};
146
147//
148// Helper functions for translating glslang representations to SPIR-V enumerants.
149//
150
151// Translate glslang profile to SPIR-V source language.
152spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
153{
154 switch (profile) {
155 case ENoProfile:
156 case ECoreProfile:
157 case ECompatibilityProfile:
158 return spv::SourceLanguageGLSL;
159 case EEsProfile:
160 return spv::SourceLanguageESSL;
161 default:
162 return spv::SourceLanguageUnknown;
163 }
164}
165
166// Translate glslang language (stage) to SPIR-V execution model.
167spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
168{
169 switch (stage) {
170 case EShLangVertex: return spv::ExecutionModelVertex;
171 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
172 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
173 case EShLangGeometry: return spv::ExecutionModelGeometry;
174 case EShLangFragment: return spv::ExecutionModelFragment;
175 case EShLangCompute: return spv::ExecutionModelGLCompute;
176 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700177 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600178 return spv::ExecutionModelFragment;
179 }
180}
181
182// Translate glslang type to SPIR-V storage class.
183spv::StorageClass TranslateStorageClass(const glslang::TType& type)
184{
185 if (type.getQualifier().isPipeInput())
186 return spv::StorageClassInput;
187 else if (type.getQualifier().isPipeOutput())
188 return spv::StorageClassOutput;
189 else if (type.getQualifier().isUniformOrBuffer()) {
190 if (type.getBasicType() == glslang::EbtBlock)
191 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800192 else if (type.getBasicType() == glslang::EbtAtomicUint)
193 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600194 else
195 return spv::StorageClassUniformConstant;
196 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
197 } else {
198 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700199 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
200 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600201 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
202 case glslang::EvqTemporary: return spv::StorageClassFunction;
203 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700204 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600205 return spv::StorageClassFunction;
206 }
207 }
208}
209
210// Translate glslang sampler type to SPIR-V dimensionality.
211spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
212{
213 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700214 case glslang::Esd1D: return spv::Dim1D;
215 case glslang::Esd2D: return spv::Dim2D;
216 case glslang::Esd3D: return spv::Dim3D;
217 case glslang::EsdCube: return spv::DimCube;
218 case glslang::EsdRect: return spv::DimRect;
219 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich140f3df2015-06-26 16:58:36 -0600220 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700221 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600222 return spv::Dim2D;
223 }
224}
225
226// Translate glslang type to SPIR-V precision decorations.
227spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
228{
229 switch (type.getQualifier().precision) {
John Kessenich5e4b1242015-08-06 22:53:06 -0600230 case glslang::EpqLow: return spv::DecorationRelaxedPrecision; // TODO: Map instead to 16-bit types?
231 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
232 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600233 default:
234 return spv::NoPrecision;
235 }
236}
237
238// Translate glslang type to SPIR-V block decorations.
239spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
240{
241 if (type.getBasicType() == glslang::EbtBlock) {
242 switch (type.getQualifier().storage) {
243 case glslang::EvqUniform: return spv::DecorationBlock;
244 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
245 case glslang::EvqVaryingIn: return spv::DecorationBlock;
246 case glslang::EvqVaryingOut: return spv::DecorationBlock;
247 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700248 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600249 break;
250 }
251 }
252
253 return (spv::Decoration)spv::BadValue;
254}
255
256// Translate glslang type to SPIR-V layout decorations.
257spv::Decoration TranslateLayoutDecoration(const glslang::TType& type)
258{
259 if (type.isMatrix()) {
260 switch (type.getQualifier().layoutMatrix) {
261 case glslang::ElmRowMajor:
262 return spv::DecorationRowMajor;
263 default:
264 return spv::DecorationColMajor;
265 }
266 } else {
267 switch (type.getBasicType()) {
268 default:
269 return (spv::Decoration)spv::BadValue;
270 break;
271 case glslang::EbtBlock:
272 switch (type.getQualifier().storage) {
273 case glslang::EvqUniform:
274 case glslang::EvqBuffer:
275 switch (type.getQualifier().layoutPacking) {
276 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600277 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
278 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600279 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600280 }
281 case glslang::EvqVaryingIn:
282 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700283 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600284 return (spv::Decoration)spv::BadValue;
285 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700286 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600287 return (spv::Decoration)spv::BadValue;
288 }
289 }
290 }
291}
292
293// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700294// Returns spv::Decoration(spv::BadValue) when no decoration
295// should be applied.
John Kessenich140f3df2015-06-26 16:58:36 -0600296spv::Decoration TranslateInterpolationDecoration(const glslang::TType& type)
297{
John Kessenich55e7d112015-11-15 21:33:39 -0700298 if (type.getQualifier().smooth) {
299 // Smooth decoration doesn't exist in SPIR-V 1.0
300 return (spv::Decoration)spv::BadValue;
301 }
John Kessenich140f3df2015-06-26 16:58:36 -0600302 if (type.getQualifier().nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700303 return spv::DecorationNoPerspective;
John Kessenich140f3df2015-06-26 16:58:36 -0600304 else if (type.getQualifier().patch)
305 return spv::DecorationPatch;
306 else if (type.getQualifier().flat)
307 return spv::DecorationFlat;
308 else if (type.getQualifier().centroid)
309 return spv::DecorationCentroid;
310 else if (type.getQualifier().sample)
311 return spv::DecorationSample;
312 else
313 return (spv::Decoration)spv::BadValue;
314}
315
316// If glslang type is invaraiant, return SPIR-V invariant decoration.
317spv::Decoration TranslateInvariantDecoration(const glslang::TType& type)
318{
319 if (type.getQualifier().invariant)
320 return spv::DecorationInvariant;
321 else
322 return (spv::Decoration)spv::BadValue;
323}
324
325// Translate glslang built-in variable to SPIR-V built in decoration.
326spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
327{
328 switch (builtIn) {
329 case glslang::EbvPosition: return spv::BuiltInPosition;
330 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600331 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
332 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
333 case glslang::EbvVertexId: return spv::BuiltInVertexId;
334 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenichda581a22015-10-14 14:10:30 -0600335 case glslang::EbvBaseVertex:
336 case glslang::EbvBaseInstance:
337 case glslang::EbvDrawId:
338 // TODO: Add SPIR-V builtin ID.
339 spv::MissingFunctionality("Draw parameters");
340 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600341 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
342 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
343 case glslang::EbvLayer: return spv::BuiltInLayer;
344 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
345 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
346 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
347 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
348 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
349 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
350 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
351 case glslang::EbvFace: return spv::BuiltInFrontFacing;
352 case glslang::EbvSampleId: return spv::BuiltInSampleId;
353 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
354 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
John Kessenich140f3df2015-06-26 16:58:36 -0600355 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
356 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
357 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
358 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
359 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
360 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
361 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
362 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
363 default: return (spv::BuiltIn)spv::BadValue;
364 }
365}
366
Rex Xufc618912015-09-09 16:42:49 +0800367// Translate glslang image layout format to SPIR-V image format.
368spv::ImageFormat TranslateImageFormat(const glslang::TType& type)
369{
370 assert(type.getBasicType() == glslang::EbtSampler);
371
372 switch (type.getQualifier().layoutFormat) {
373 case glslang::ElfNone: return spv::ImageFormatUnknown;
374 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
375 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
376 case glslang::ElfR32f: return spv::ImageFormatR32f;
377 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
378 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
379 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
380 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
381 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
382 case glslang::ElfR16f: return spv::ImageFormatR16f;
383 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
384 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
385 case glslang::ElfRg16: return spv::ImageFormatRg16;
386 case glslang::ElfRg8: return spv::ImageFormatRg8;
387 case glslang::ElfR16: return spv::ImageFormatR16;
388 case glslang::ElfR8: return spv::ImageFormatR8;
389 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
390 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
391 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
392 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
393 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
394 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
395 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
396 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
397 case glslang::ElfR32i: return spv::ImageFormatR32i;
398 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
399 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
400 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
401 case glslang::ElfR16i: return spv::ImageFormatR16i;
402 case glslang::ElfR8i: return spv::ImageFormatR8i;
403 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
404 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
405 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
406 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
407 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
408 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
409 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
410 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
411 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
412 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
413 default: return (spv::ImageFormat)spv::BadValue;
414 }
415}
416
John Kessenich140f3df2015-06-26 16:58:36 -0600417//
418// Implement the TGlslangToSpvTraverser class.
419//
420
421TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
422 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700423 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600424 inMain(false), mainTerminated(false), linkageOnly(false),
425 glslangIntermediate(glslangIntermediate)
426{
427 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
428
429 builder.clearAccessChain();
430 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
431 stdBuiltins = builder.import("GLSL.std.450");
432 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
433 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700434 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600435
436 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600437 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
438 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600439 builder.addSourceExtension(it->c_str());
440
441 // Add the top-level modes for this shader.
442
443 if (glslangIntermediate->getXfbMode())
444 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
445
446 unsigned int mode;
447 switch (glslangIntermediate->getStage()) {
448 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600449 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600450 break;
451
452 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600453 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600454 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
455 break;
456
457 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600458 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600459 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700460 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
461 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
462 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600463 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600464 }
465 if (mode != spv::BadValue)
466 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
467
John Kesseniche6903322015-10-13 16:29:02 -0600468 switch (glslangIntermediate->getVertexSpacing()) {
469 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
470 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
471 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
472 default: mode = spv::BadValue; break;
473 }
474 if (mode != spv::BadValue)
475 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
476
477 switch (glslangIntermediate->getVertexOrder()) {
478 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
479 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
480 default: mode = spv::BadValue; break;
481 }
482 if (mode != spv::BadValue)
483 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
484
485 if (glslangIntermediate->getPointMode())
486 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600487 break;
488
489 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600490 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600491 switch (glslangIntermediate->getInputPrimitive()) {
492 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
493 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
494 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700495 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600496 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
497 default: mode = spv::BadValue; break;
498 }
499 if (mode != spv::BadValue)
500 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600501
John Kessenich140f3df2015-06-26 16:58:36 -0600502 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
503
504 switch (glslangIntermediate->getOutputPrimitive()) {
505 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
506 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
507 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
508 default: mode = spv::BadValue; break;
509 }
510 if (mode != spv::BadValue)
511 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
512 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
513 break;
514
515 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600516 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600517 if (glslangIntermediate->getPixelCenterInteger())
518 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600519
John Kessenich140f3df2015-06-26 16:58:36 -0600520 if (glslangIntermediate->getOriginUpperLeft())
521 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600522 else
523 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600524
525 if (glslangIntermediate->getEarlyFragmentTests())
526 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
527
528 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600529 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
530 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
531 default: mode = spv::BadValue; break;
532 }
533 if (mode != spv::BadValue)
534 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
535
536 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
537 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600538 break;
539
540 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600541 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600542 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
543 glslangIntermediate->getLocalSize(1),
544 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600545 break;
546
547 default:
548 break;
549 }
550
551}
552
553TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
554{
555 if (! mainTerminated) {
556 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
557 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600558 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600559 }
560}
561
562//
563// Implement the traversal functions.
564//
565// Return true from interior nodes to have the external traversal
566// continue on to children. Return false if children were
567// already processed.
568//
569
570//
571// Symbols can turn into
572// - uniform/input reads
573// - output writes
574// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
575// - something simple that degenerates into the last bullet
576//
577void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
578{
579 // getSymbolId() will set up all the IO decorations on the first call.
580 // Formal function parameters were mapped during makeFunctions().
581 spv::Id id = getSymbolId(symbol);
582
583 if (! linkageOnly) {
584 // Prepare to generate code for the access
585
586 // L-value chains will be computed left to right. We're on the symbol now,
587 // which is the left-most part of the access chain, so now is "clear" time,
588 // followed by setting the base.
589 builder.clearAccessChain();
590
591 // For now, we consider all user variables as being in memory, so they are pointers,
592 // except for "const in" arguments to a function, which are an intermediate object.
593 // See comments in handleUserFunctionCall().
594 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
595 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
596 builder.setAccessChainRValue(id);
597 else
598 builder.setAccessChainLValue(id);
John Kessenich55e7d112015-11-15 21:33:39 -0700599 } else {
600 // finish off the entry-point SPV instruction by adding the Input/Output <id>
601 spv::StorageClass sc = builder.getStorageClass(id);
602 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
603 entryPoint->addIdOperand(id);
John Kessenich140f3df2015-06-26 16:58:36 -0600604 }
605}
606
607bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
608{
609 // First, handle special cases
610 switch (node->getOp()) {
611 case glslang::EOpAssign:
612 case glslang::EOpAddAssign:
613 case glslang::EOpSubAssign:
614 case glslang::EOpMulAssign:
615 case glslang::EOpVectorTimesMatrixAssign:
616 case glslang::EOpVectorTimesScalarAssign:
617 case glslang::EOpMatrixTimesScalarAssign:
618 case glslang::EOpMatrixTimesMatrixAssign:
619 case glslang::EOpDivAssign:
620 case glslang::EOpModAssign:
621 case glslang::EOpAndAssign:
622 case glslang::EOpInclusiveOrAssign:
623 case glslang::EOpExclusiveOrAssign:
624 case glslang::EOpLeftShiftAssign:
625 case glslang::EOpRightShiftAssign:
626 // A bin-op assign "a += b" means the same thing as "a = a + b"
627 // where a is evaluated before b. For a simple assignment, GLSL
628 // says to evaluate the left before the right. So, always, left
629 // node then right node.
630 {
631 // get the left l-value, save it away
632 builder.clearAccessChain();
633 node->getLeft()->traverse(this);
634 spv::Builder::AccessChain lValue = builder.getAccessChain();
635
636 // evaluate the right
637 builder.clearAccessChain();
638 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600639 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600640
641 if (node->getOp() != glslang::EOpAssign) {
642 // the left is also an r-value
643 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600644 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600645
646 // do the operation
647 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
648 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
649 node->getType().getBasicType());
650
651 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700652 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600653 }
654
655 // store the result
656 builder.setAccessChain(lValue);
657 builder.accessChainStore(rValue);
658
659 // assignments are expressions having an rValue after they are evaluated...
660 builder.clearAccessChain();
661 builder.setAccessChainRValue(rValue);
662 }
663 return false;
664 case glslang::EOpIndexDirect:
665 case glslang::EOpIndexDirectStruct:
666 {
667 // Get the left part of the access chain.
668 node->getLeft()->traverse(this);
669
670 // Add the next element in the chain
671
John Kessenich55e7d112015-11-15 21:33:39 -0700672 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600673 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
674 // This may be, e.g., an anonymous block-member selection, which generally need
675 // index remapping due to hidden members in anonymous blocks.
676 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700677 assert(remapper.size() > 0);
678 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600679 }
680
681 if (! node->getLeft()->getType().isArray() &&
682 node->getLeft()->getType().isVector() &&
683 node->getOp() == glslang::EOpIndexDirect) {
684 // This is essentially a hard-coded vector swizzle of size 1,
685 // so short circuit the access-chain stuff with a swizzle.
686 std::vector<unsigned> swizzle;
687 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600688 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600689 } else {
690 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600691 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600692 }
693 }
694 return false;
695 case glslang::EOpIndexIndirect:
696 {
697 // Structure or array or vector indirection.
698 // Will use native SPIR-V access-chain for struct and array indirection;
699 // matrices are arrays of vectors, so will also work for a matrix.
700 // Will use the access chain's 'component' for variable index into a vector.
701
702 // This adapter is building access chains left to right.
703 // Set up the access chain to the left.
704 node->getLeft()->traverse(this);
705
706 // save it so that computing the right side doesn't trash it
707 spv::Builder::AccessChain partial = builder.getAccessChain();
708
709 // compute the next index in the chain
710 builder.clearAccessChain();
711 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600712 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600713
714 // restore the saved access chain
715 builder.setAccessChain(partial);
716
717 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600718 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600719 else
John Kessenichfa668da2015-09-13 14:46:30 -0600720 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600721 }
722 return false;
723 case glslang::EOpVectorSwizzle:
724 {
725 node->getLeft()->traverse(this);
726 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
727 std::vector<unsigned> swizzle;
728 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
729 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600730 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600731 }
732 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600733 case glslang::EOpLogicalOr:
734 case glslang::EOpLogicalAnd:
735 {
736
737 // These may require short circuiting, but can sometimes be done as straight
738 // binary operations. The right operand must be short circuited if it has
739 // side effects, and should probably be if it is complex.
740 if (isTrivial(node->getRight()->getAsTyped()))
741 break; // handle below as a normal binary operation
742 // otherwise, we need to do dynamic short circuiting on the right operand
743 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
744 builder.clearAccessChain();
745 builder.setAccessChainRValue(result);
746 }
747 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600748 default:
749 break;
750 }
751
752 // Assume generic binary op...
753
754 // Get the operands
755 builder.clearAccessChain();
756 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600757 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600758
759 builder.clearAccessChain();
760 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600761 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600762
763 spv::Id result;
764 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
765
766 result = createBinaryOperation(node->getOp(), precision,
767 convertGlslangToSpvType(node->getType()), left, right,
768 node->getLeft()->getType().getBasicType());
769
770 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700771 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich140f3df2015-06-26 16:58:36 -0600772 } else {
773 builder.clearAccessChain();
774 builder.setAccessChainRValue(result);
775
776 return false;
777 }
778
779 return true;
780}
781
782bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
783{
John Kessenichfc51d282015-08-19 13:34:18 -0600784 spv::Id result = spv::NoResult;
785
786 // try texturing first
787 result = createImageTextureFunctionCall(node);
788 if (result != spv::NoResult) {
789 builder.clearAccessChain();
790 builder.setAccessChainRValue(result);
791
792 return false; // done with this node
793 }
794
795 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600796
797 if (node->getOp() == glslang::EOpArrayLength) {
798 // Quite special; won't want to evaluate the operand.
799
800 // Normal .length() would have been constant folded by the front-end.
801 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600802 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600803 assert(node->getOperand()->getType().isRuntimeSizedArray());
804 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
805 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600806 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
807 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600808
809 builder.clearAccessChain();
810 builder.setAccessChainRValue(length);
811
812 return false;
813 }
814
John Kessenichfc51d282015-08-19 13:34:18 -0600815 // Start by evaluating the operand
816
John Kessenich140f3df2015-06-26 16:58:36 -0600817 builder.clearAccessChain();
818 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800819
Rex Xufc618912015-09-09 16:42:49 +0800820 spv::Id operand = spv::NoResult;
821
822 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
823 node->getOp() == glslang::EOpAtomicCounterDecrement ||
824 node->getOp() == glslang::EOpAtomicCounter)
825 operand = builder.accessChainGetLValue(); // Special case l-value operands
826 else
Rex Xu30f92582015-09-14 10:38:56 +0800827 operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600828
829 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
830
831 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600832 if (! result)
833 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600834
835 // if not, then possibly an operation
836 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700837 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600838
839 if (result) {
840 builder.clearAccessChain();
841 builder.setAccessChainRValue(result);
842
843 return false; // done with this node
844 }
845
846 // it must be a special case, check...
847 switch (node->getOp()) {
848 case glslang::EOpPostIncrement:
849 case glslang::EOpPostDecrement:
850 case glslang::EOpPreIncrement:
851 case glslang::EOpPreDecrement:
852 {
853 // we need the integer value "1" or the floating point "1.0" to add/subtract
854 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
855 builder.makeFloatConstant(1.0F) :
856 builder.makeIntConstant(1);
857 glslang::TOperator op;
858 if (node->getOp() == glslang::EOpPreIncrement ||
859 node->getOp() == glslang::EOpPostIncrement)
860 op = glslang::EOpAdd;
861 else
862 op = glslang::EOpSub;
863
864 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
865 convertGlslangToSpvType(node->getType()), operand, one,
866 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -0700867 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600868
869 // The result of operation is always stored, but conditionally the
870 // consumed result. The consumed result is always an r-value.
871 builder.accessChainStore(result);
872 builder.clearAccessChain();
873 if (node->getOp() == glslang::EOpPreIncrement ||
874 node->getOp() == glslang::EOpPreDecrement)
875 builder.setAccessChainRValue(result);
876 else
877 builder.setAccessChainRValue(operand);
878 }
879
880 return false;
881
882 case glslang::EOpEmitStreamVertex:
883 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
884 return false;
885 case glslang::EOpEndStreamPrimitive:
886 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
887 return false;
888
889 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700890 spv::MissingFunctionality("unknown glslang unary");
John Kessenich140f3df2015-06-26 16:58:36 -0600891 break;
892 }
893
894 return true;
895}
896
897bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
898{
John Kessenichfc51d282015-08-19 13:34:18 -0600899 spv::Id result = spv::NoResult;
900
901 // try texturing
902 result = createImageTextureFunctionCall(node);
903 if (result != spv::NoResult) {
904 builder.clearAccessChain();
905 builder.setAccessChainRValue(result);
906
907 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600908 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800909 // "imageStore" is a special case, which has no result
910 return false;
911 }
John Kessenichfc51d282015-08-19 13:34:18 -0600912
John Kessenich140f3df2015-06-26 16:58:36 -0600913 glslang::TOperator binOp = glslang::EOpNull;
914 bool reduceComparison = true;
915 bool isMatrix = false;
916 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600917 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600918
919 assert(node->getOp());
920
921 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
922
923 switch (node->getOp()) {
924 case glslang::EOpSequence:
925 {
926 if (preVisit)
927 ++sequenceDepth;
928 else
929 --sequenceDepth;
930
931 if (sequenceDepth == 1) {
932 // If this is the parent node of all the functions, we want to see them
933 // early, so all call points have actual SPIR-V functions to reference.
934 // In all cases, still let the traverser visit the children for us.
935 makeFunctions(node->getAsAggregate()->getSequence());
936
937 // Also, we want all globals initializers to go into the entry of main(), before
938 // anything else gets there, so visit out of order, doing them all now.
939 makeGlobalInitializers(node->getAsAggregate()->getSequence());
940
941 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
942 // so do them manually.
943 visitFunctions(node->getAsAggregate()->getSequence());
944
945 return false;
946 }
947
948 return true;
949 }
950 case glslang::EOpLinkerObjects:
951 {
952 if (visit == glslang::EvPreVisit)
953 linkageOnly = true;
954 else
955 linkageOnly = false;
956
957 return true;
958 }
959 case glslang::EOpComma:
960 {
961 // processing from left to right naturally leaves the right-most
962 // lying around in the access chain
963 glslang::TIntermSequence& glslangOperands = node->getSequence();
964 for (int i = 0; i < (int)glslangOperands.size(); ++i)
965 glslangOperands[i]->traverse(this);
966
967 return false;
968 }
969 case glslang::EOpFunction:
970 if (visit == glslang::EvPreVisit) {
971 if (isShaderEntrypoint(node)) {
972 inMain = true;
973 builder.setBuildPoint(shaderEntry->getLastBlock());
974 } else {
975 handleFunctionEntry(node);
976 }
977 } else {
978 if (inMain)
979 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -0600980 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600981 inMain = false;
982 }
983
984 return true;
985 case glslang::EOpParameters:
986 // Parameters will have been consumed by EOpFunction processing, but not
987 // the body, so we still visited the function node's children, making this
988 // child redundant.
989 return false;
990 case glslang::EOpFunctionCall:
991 {
992 if (node->isUserDefined())
993 result = handleUserFunctionCall(node);
John Kessenich55e7d112015-11-15 21:33:39 -0700994 assert(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600995 builder.clearAccessChain();
996 builder.setAccessChainRValue(result);
997
998 return false;
999 }
1000 case glslang::EOpConstructMat2x2:
1001 case glslang::EOpConstructMat2x3:
1002 case glslang::EOpConstructMat2x4:
1003 case glslang::EOpConstructMat3x2:
1004 case glslang::EOpConstructMat3x3:
1005 case glslang::EOpConstructMat3x4:
1006 case glslang::EOpConstructMat4x2:
1007 case glslang::EOpConstructMat4x3:
1008 case glslang::EOpConstructMat4x4:
1009 case glslang::EOpConstructDMat2x2:
1010 case glslang::EOpConstructDMat2x3:
1011 case glslang::EOpConstructDMat2x4:
1012 case glslang::EOpConstructDMat3x2:
1013 case glslang::EOpConstructDMat3x3:
1014 case glslang::EOpConstructDMat3x4:
1015 case glslang::EOpConstructDMat4x2:
1016 case glslang::EOpConstructDMat4x3:
1017 case glslang::EOpConstructDMat4x4:
1018 isMatrix = true;
1019 // fall through
1020 case glslang::EOpConstructFloat:
1021 case glslang::EOpConstructVec2:
1022 case glslang::EOpConstructVec3:
1023 case glslang::EOpConstructVec4:
1024 case glslang::EOpConstructDouble:
1025 case glslang::EOpConstructDVec2:
1026 case glslang::EOpConstructDVec3:
1027 case glslang::EOpConstructDVec4:
1028 case glslang::EOpConstructBool:
1029 case glslang::EOpConstructBVec2:
1030 case glslang::EOpConstructBVec3:
1031 case glslang::EOpConstructBVec4:
1032 case glslang::EOpConstructInt:
1033 case glslang::EOpConstructIVec2:
1034 case glslang::EOpConstructIVec3:
1035 case glslang::EOpConstructIVec4:
1036 case glslang::EOpConstructUint:
1037 case glslang::EOpConstructUVec2:
1038 case glslang::EOpConstructUVec3:
1039 case glslang::EOpConstructUVec4:
1040 case glslang::EOpConstructStruct:
1041 {
1042 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001043 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001044 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1045 spv::Id constructed;
1046 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1047 std::vector<spv::Id> constituents;
1048 for (int c = 0; c < (int)arguments.size(); ++c)
1049 constituents.push_back(arguments[c]);
1050 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001051 } else if (isMatrix)
1052 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1053 else
1054 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001055
1056 builder.clearAccessChain();
1057 builder.setAccessChainRValue(constructed);
1058
1059 return false;
1060 }
1061
1062 // These six are component-wise compares with component-wise results.
1063 // Forward on to createBinaryOperation(), requesting a vector result.
1064 case glslang::EOpLessThan:
1065 case glslang::EOpGreaterThan:
1066 case glslang::EOpLessThanEqual:
1067 case glslang::EOpGreaterThanEqual:
1068 case glslang::EOpVectorEqual:
1069 case glslang::EOpVectorNotEqual:
1070 {
1071 // Map the operation to a binary
1072 binOp = node->getOp();
1073 reduceComparison = false;
1074 switch (node->getOp()) {
1075 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1076 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1077 default: binOp = node->getOp(); break;
1078 }
1079
1080 break;
1081 }
1082 case glslang::EOpMul:
1083 // compontent-wise matrix multiply
1084 binOp = glslang::EOpMul;
1085 break;
1086 case glslang::EOpOuterProduct:
1087 // two vectors multiplied to make a matrix
1088 binOp = glslang::EOpOuterProduct;
1089 break;
1090 case glslang::EOpDot:
1091 {
1092 // for scalar dot product, use multiply
1093 glslang::TIntermSequence& glslangOperands = node->getSequence();
1094 if (! glslangOperands[0]->getAsTyped()->isVector())
1095 binOp = glslang::EOpMul;
1096 break;
1097 }
1098 case glslang::EOpMod:
1099 // when an aggregate, this is the floating-point mod built-in function,
1100 // which can be emitted by the one in createBinaryOperation()
1101 binOp = glslang::EOpMod;
1102 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001103 case glslang::EOpEmitVertex:
1104 case glslang::EOpEndPrimitive:
1105 case glslang::EOpBarrier:
1106 case glslang::EOpMemoryBarrier:
1107 case glslang::EOpMemoryBarrierAtomicCounter:
1108 case glslang::EOpMemoryBarrierBuffer:
1109 case glslang::EOpMemoryBarrierImage:
1110 case glslang::EOpMemoryBarrierShared:
1111 case glslang::EOpGroupMemoryBarrier:
1112 noReturnValue = true;
1113 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1114 break;
1115
John Kessenich426394d2015-07-23 10:22:48 -06001116 case glslang::EOpAtomicAdd:
1117 case glslang::EOpAtomicMin:
1118 case glslang::EOpAtomicMax:
1119 case glslang::EOpAtomicAnd:
1120 case glslang::EOpAtomicOr:
1121 case glslang::EOpAtomicXor:
1122 case glslang::EOpAtomicExchange:
1123 case glslang::EOpAtomicCompSwap:
1124 atomic = true;
1125 break;
1126
John Kessenich140f3df2015-06-26 16:58:36 -06001127 default:
1128 break;
1129 }
1130
1131 //
1132 // See if it maps to a regular operation.
1133 //
John Kessenich140f3df2015-06-26 16:58:36 -06001134 if (binOp != glslang::EOpNull) {
1135 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1136 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1137 assert(left && right);
1138
1139 builder.clearAccessChain();
1140 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001141 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001142
1143 builder.clearAccessChain();
1144 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001145 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001146
1147 result = createBinaryOperation(binOp, precision,
1148 convertGlslangToSpvType(node->getType()), leftId, rightId,
1149 left->getType().getBasicType(), reduceComparison);
1150
1151 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001152 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001153 builder.clearAccessChain();
1154 builder.setAccessChainRValue(result);
1155
1156 return false;
1157 }
1158
John Kessenich426394d2015-07-23 10:22:48 -06001159 //
1160 // Create the list of operands.
1161 //
John Kessenich140f3df2015-06-26 16:58:36 -06001162 glslang::TIntermSequence& glslangOperands = node->getSequence();
1163 std::vector<spv::Id> operands;
1164 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1165 builder.clearAccessChain();
1166 glslangOperands[arg]->traverse(this);
1167
1168 // special case l-value operands; there are just a few
1169 bool lvalue = false;
1170 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001171 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001172 case glslang::EOpModf:
1173 if (arg == 1)
1174 lvalue = true;
1175 break;
Rex Xud4782c12015-09-06 16:30:11 +08001176 case glslang::EOpAtomicAdd:
1177 case glslang::EOpAtomicMin:
1178 case glslang::EOpAtomicMax:
1179 case glslang::EOpAtomicAnd:
1180 case glslang::EOpAtomicOr:
1181 case glslang::EOpAtomicXor:
1182 case glslang::EOpAtomicExchange:
1183 case glslang::EOpAtomicCompSwap:
1184 if (arg == 0)
1185 lvalue = true;
1186 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001187 case glslang::EOpAddCarry:
1188 case glslang::EOpSubBorrow:
1189 if (arg == 2)
1190 lvalue = true;
1191 break;
1192 case glslang::EOpUMulExtended:
1193 case glslang::EOpIMulExtended:
1194 if (arg >= 2)
1195 lvalue = true;
1196 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001197 default:
1198 break;
1199 }
1200 if (lvalue)
1201 operands.push_back(builder.accessChainGetLValue());
1202 else
John Kessenichfa668da2015-09-13 14:46:30 -06001203 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001204 }
John Kessenich426394d2015-07-23 10:22:48 -06001205
1206 if (atomic) {
1207 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001208 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001209 } else {
1210 // Pass through to generic operations.
1211 switch (glslangOperands.size()) {
1212 case 0:
1213 result = createNoArgOperation(node->getOp());
1214 break;
1215 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001216 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001217 break;
1218 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001219 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001220 break;
1221 }
John Kessenich140f3df2015-06-26 16:58:36 -06001222 }
1223
1224 if (noReturnValue)
1225 return false;
1226
1227 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001228 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich140f3df2015-06-26 16:58:36 -06001229 return true;
1230 } else {
1231 builder.clearAccessChain();
1232 builder.setAccessChainRValue(result);
1233 return false;
1234 }
1235}
1236
1237bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1238{
1239 // This path handles both if-then-else and ?:
1240 // The if-then-else has a node type of void, while
1241 // ?: has a non-void node type
1242 spv::Id result = 0;
1243 if (node->getBasicType() != glslang::EbtVoid) {
1244 // don't handle this as just on-the-fly temporaries, because there will be two names
1245 // and better to leave SSA to later passes
1246 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1247 }
1248
1249 // emit the condition before doing anything with selection
1250 node->getCondition()->traverse(this);
1251
1252 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001253 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001254
1255 if (node->getTrueBlock()) {
1256 // emit the "then" statement
1257 node->getTrueBlock()->traverse(this);
1258 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001259 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001260 }
1261
1262 if (node->getFalseBlock()) {
1263 ifBuilder.makeBeginElse();
1264 // emit the "else" statement
1265 node->getFalseBlock()->traverse(this);
1266 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001267 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001268 }
1269
1270 ifBuilder.makeEndIf();
1271
1272 if (result) {
1273 // GLSL only has r-values as the result of a :?, but
1274 // if we have an l-value, that can be more efficient if it will
1275 // become the base of a complex r-value expression, because the
1276 // next layer copies r-values into memory to use the access-chain mechanism
1277 builder.clearAccessChain();
1278 builder.setAccessChainLValue(result);
1279 }
1280
1281 return false;
1282}
1283
1284bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1285{
1286 // emit and get the condition before doing anything with switch
1287 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001288 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001289
1290 // browse the children to sort out code segments
1291 int defaultSegment = -1;
1292 std::vector<TIntermNode*> codeSegments;
1293 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1294 std::vector<int> caseValues;
1295 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1296 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1297 TIntermNode* child = *c;
1298 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001299 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001300 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001301 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001302 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1303 } else
1304 codeSegments.push_back(child);
1305 }
1306
1307 // handle the case where the last code segment is missing, due to no code
1308 // statements between the last case and the end of the switch statement
1309 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1310 (int)codeSegments.size() == defaultSegment)
1311 codeSegments.push_back(nullptr);
1312
1313 // make the switch statement
1314 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001315 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001316
1317 // emit all the code in the segments
1318 breakForLoop.push(false);
1319 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1320 builder.nextSwitchSegment(segmentBlocks, s);
1321 if (codeSegments[s])
1322 codeSegments[s]->traverse(this);
1323 else
1324 builder.addSwitchBreak();
1325 }
1326 breakForLoop.pop();
1327
1328 builder.endSwitch(segmentBlocks);
1329
1330 return false;
1331}
1332
1333void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1334{
1335 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001336 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001337
1338 builder.clearAccessChain();
1339 builder.setAccessChainRValue(constant);
1340}
1341
1342bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1343{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001344 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001345 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001346 if (node->testFirst() && node->getTest()) {
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001347 builder.setBuildPoint(&blocks.head);
John Kessenich140f3df2015-06-26 16:58:36 -06001348 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001349 spv::Id condition =
1350 builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
1351 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
1352 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1353
1354 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001355 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001356 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001357 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001358 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001359 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001360
1361 builder.setBuildPoint(&blocks.continue_target);
1362 if (node->getTerminal())
1363 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001364 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001365 } else {
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001366 // Spec requires back edges to target header blocks, and every header
1367 // block must dominate its merge block. Create an empty header block
1368 // here to ensure these conditions are met even when body contains
1369 // non-trivial control flow.
1370 builder.setBuildPoint(&blocks.head);
1371 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001372 builder.createBranch(&blocks.body);
1373
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001374 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001375 builder.setBuildPoint(&blocks.body);
1376 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001377 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001378 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001379 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001380
1381 builder.setBuildPoint(&blocks.continue_target);
1382 if (node->getTerminal())
1383 node->getTerminal()->traverse(this);
1384 if (node->getTest()) {
1385 node->getTest()->traverse(this);
1386 spv::Id condition =
1387 builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001388 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001389 } else {
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001390 // TODO: unless there was a break instruction somewhere in the body,
1391 // this is an infinite loop, so we should abort code generation with
1392 // a warning. As it stands now, nothing will jump to the merge
1393 // block, and it may be dropped as unreachable by the SPIR-V dumper.
1394 // That, in turn, will result in a non-existing %ID in the LoopMerge
1395 // above.
1396 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001397 }
John Kessenich140f3df2015-06-26 16:58:36 -06001398 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001399 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001400 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001401 return false;
1402}
1403
1404bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1405{
1406 if (node->getExpression())
1407 node->getExpression()->traverse(this);
1408
1409 switch (node->getFlowOp()) {
1410 case glslang::EOpKill:
1411 builder.makeDiscard();
1412 break;
1413 case glslang::EOpBreak:
1414 if (breakForLoop.top())
1415 builder.createLoopExit();
1416 else
1417 builder.addSwitchBreak();
1418 break;
1419 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001420 builder.createLoopContinue();
1421 break;
1422 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001423 if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001424 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001425 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001426 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001427
1428 builder.clearAccessChain();
1429 break;
1430
1431 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001432 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001433 break;
1434 }
1435
1436 return false;
1437}
1438
1439spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1440{
1441 // First, steer off constants, which are not SPIR-V variables, but
1442 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001443 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001444 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001445 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001446 }
1447
1448 // Now, handle actual variables
1449 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1450 spv::Id spvType = convertGlslangToSpvType(node->getType());
1451
1452 const char* name = node->getName().c_str();
1453 if (glslang::IsAnonymous(name))
1454 name = "";
1455
1456 return builder.createVariable(storageClass, spvType, name);
1457}
1458
1459// Return type Id of the sampled type.
1460spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1461{
1462 switch (sampler.type) {
1463 case glslang::EbtFloat: return builder.makeFloatType(32);
1464 case glslang::EbtInt: return builder.makeIntType(32);
1465 case glslang::EbtUint: return builder.makeUintType(32);
1466 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001467 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001468 return builder.makeFloatType(32);
1469 }
1470}
1471
John Kessenich31ed4832015-09-09 17:51:38 -06001472// Convert from a glslang type to an SPV type, by calling into
1473// recursive version of this function.
John Kessenich140f3df2015-06-26 16:58:36 -06001474spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1475{
John Kessenich31ed4832015-09-09 17:51:38 -06001476 return convertGlslangToSpvType(type, requiresExplicitLayout(type));
1477}
1478
1479// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1480// explicitLayout can be kept the same throughout the heirarchical recursive walk.
1481spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout)
1482{
John Kessenich140f3df2015-06-26 16:58:36 -06001483 spv::Id spvType = 0;
1484
1485 switch (type.getBasicType()) {
1486 case glslang::EbtVoid:
1487 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001488 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001489 break;
1490 case glslang::EbtFloat:
1491 spvType = builder.makeFloatType(32);
1492 break;
1493 case glslang::EbtDouble:
1494 spvType = builder.makeFloatType(64);
1495 break;
1496 case glslang::EbtBool:
1497 spvType = builder.makeBoolType();
1498 break;
1499 case glslang::EbtInt:
1500 spvType = builder.makeIntType(32);
1501 break;
1502 case glslang::EbtUint:
1503 spvType = builder.makeUintType(32);
1504 break;
John Kessenich426394d2015-07-23 10:22:48 -06001505 case glslang::EbtAtomicUint:
1506 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1507 spvType = builder.makeUintType(32);
1508 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001509 case glslang::EbtSampler:
1510 {
1511 const glslang::TSampler& sampler = type.getSampler();
John Kessenich55e7d112015-11-15 21:33:39 -07001512 // an image is present, make its type
1513 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1514 sampler.image ? 2 : 1, TranslateImageFormat(type));
1515 if (! sampler.image) {
1516 spvType = builder.makeSampledImageType(spvType);
1517 }
1518 }
John Kessenich140f3df2015-06-26 16:58:36 -06001519 break;
1520 case glslang::EbtStruct:
1521 case glslang::EbtBlock:
1522 {
1523 // If we've seen this struct type, return it
1524 const glslang::TTypeList* glslangStruct = type.getStruct();
1525 std::vector<spv::Id> structFields;
1526 spvType = structMap[glslangStruct];
1527 if (spvType)
1528 break;
1529
1530 // else, we haven't seen it...
1531
1532 // Create a vector of struct types for SPIR-V to consume
1533 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1534 if (type.getBasicType() == glslang::EbtBlock)
1535 memberRemapper[glslangStruct].resize(glslangStruct->size());
1536 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1537 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1538 if (glslangType.hiddenMember()) {
1539 ++memberDelta;
1540 if (type.getBasicType() == glslang::EbtBlock)
1541 memberRemapper[glslangStruct][i] = -1;
1542 } else {
1543 if (type.getBasicType() == glslang::EbtBlock)
1544 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kessenich31ed4832015-09-09 17:51:38 -06001545 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001546 }
1547 }
1548
1549 // Make the SPIR-V type
1550 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
1551 structMap[glslangStruct] = spvType;
1552
1553 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001554 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001555 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1556 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1557 int member = i;
1558 if (type.getBasicType() == glslang::EbtBlock)
1559 member = memberRemapper[glslangStruct][i];
1560 // using -1 above to indicate a hidden member
1561 if (member >= 0) {
1562 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
1563 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType));
1564 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1565 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1566 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1567 if (glslangType.getQualifier().hasLocation())
1568 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1569 if (glslangType.getQualifier().hasComponent())
1570 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1571 if (glslangType.getQualifier().hasXfbOffset())
1572 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenich31ed4832015-09-09 17:51:38 -06001573 else if (explicitLayout) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001574 // figure out what to do with offset, which is accumulating
1575 int nextOffset;
1576 updateMemberOffset(type, glslangType, offset, nextOffset);
1577 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001578 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001579 offset = nextOffset;
1580 }
John Kessenich140f3df2015-06-26 16:58:36 -06001581
John Kessenich31ed4832015-09-09 17:51:38 -06001582 if (glslangType.isMatrix() && explicitLayout) {
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001583 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType));
1584 }
1585
John Kessenich140f3df2015-06-26 16:58:36 -06001586 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001587 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1588 if (builtIn != spv::BadValue)
1589 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001590 }
1591 }
1592
1593 // Decorate the structure
1594 addDecoration(spvType, TranslateLayoutDecoration(type));
1595 addDecoration(spvType, TranslateBlockDecoration(type));
1596 if (type.getQualifier().hasStream())
1597 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1598 if (glslangIntermediate->getXfbMode()) {
1599 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001600 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001601 if (type.getQualifier().hasXfbBuffer())
1602 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1603 }
1604 }
1605 break;
1606 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001607 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001608 break;
1609 }
1610
1611 if (type.isMatrix())
1612 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1613 else {
1614 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1615 if (type.getVectorSize() > 1)
1616 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1617 }
1618
1619 if (type.isArray()) {
John Kessenichc9a80832015-09-12 12:17:44 -06001620 // Do all but the outer dimension
1621 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1622 assert(type.getArraySizes()->getDimSize(dim) > 0);
1623 spvType = builder.makeArrayType(spvType, type.getArraySizes()->getDimSize(dim));
1624 }
John Kessenich31ed4832015-09-09 17:51:38 -06001625
John Kessenichc9a80832015-09-12 12:17:44 -06001626 // Do the outer dimension, which might not be known for a runtime-sized array
1627 if (type.isRuntimeSizedArray()) {
1628 spvType = builder.makeRuntimeArray(spvType);
1629 } else {
1630 assert(type.getOuterArraySize() > 0);
1631 spvType = builder.makeArrayType(spvType, type.getOuterArraySize());
1632 }
1633
John Kessenich55e7d112015-11-15 21:33:39 -07001634 // TODO: explicit layout still needs to be done hierarchically for arrays of arrays, which
John Kessenichc9a80832015-09-12 12:17:44 -06001635 // may still require additional "link time" support from the front-end
1636 // for arrays of arrays
John Kessenich55e7d112015-11-15 21:33:39 -07001637
1638 // We need to decorate array strides for types needing explicit layout,
1639 // except for the very top if it is an array of blocks; that array is
1640 // not laid out in memory in a way needing a stride.
1641 if (explicitLayout && type.getBasicType() != glslang::EbtBlock)
John Kessenich31ed4832015-09-09 17:51:38 -06001642 builder.addDecoration(spvType, spv::DecorationArrayStride, getArrayStride(type));
John Kessenich140f3df2015-06-26 16:58:36 -06001643 }
1644
1645 return spvType;
1646}
1647
John Kessenich31ed4832015-09-09 17:51:38 -06001648bool TGlslangToSpvTraverser::requiresExplicitLayout(const glslang::TType& type) const
1649{
1650 return type.getBasicType() == glslang::EbtBlock &&
1651 type.getQualifier().layoutPacking != glslang::ElpShared &&
1652 type.getQualifier().layoutPacking != glslang::ElpPacked &&
1653 (type.getQualifier().storage == glslang::EvqUniform ||
1654 type.getQualifier().storage == glslang::EvqBuffer);
1655}
1656
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001657// Given an array type, returns the integer stride required for that array
1658int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType)
1659{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001660 int size;
John Kesseniche721f492015-12-06 19:17:49 -07001661 int stride = glslangIntermediate->getBaseAlignment(arrayType, size, arrayType.getQualifier().layoutPacking == glslang::ElpStd140);
1662 if (arrayType.isMatrix()) {
1663 // GLSL strides are set to alignments of the matrix flattened to individual rows/cols,
1664 // but SPV needs an array stride for the whole matrix, not the rows/cols
1665 if (arrayType.getQualifier().layoutMatrix == glslang::ElmRowMajor)
1666 stride *= arrayType.getMatrixRows();
1667 else
1668 stride *= arrayType.getMatrixCols();
1669 }
1670
1671 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001672}
1673
1674// Given a matrix type, returns the integer stride required for that matrix
1675// when used as a member of an interface block
1676int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType)
1677{
1678 int size;
John Kesseniche721f492015-12-06 19:17:49 -07001679 return glslangIntermediate->getBaseAlignment(matrixType, size, matrixType.getQualifier().layoutPacking == glslang::ElpStd140);
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001680}
1681
John Kessenich5e4b1242015-08-06 22:53:06 -06001682// Given a member type of a struct, realign the current offset for it, and compute
1683// the next (not yet aligned) offset for the next member, which will get aligned
1684// on the next call.
1685// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1686// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1687// -1 means a non-forced member offset (no decoration needed).
1688void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset)
1689{
1690 // this will get a positive value when deemed necessary
1691 nextOffset = -1;
1692
1693 bool forceOffset = structType.getQualifier().layoutPacking == glslang::ElpStd140 ||
1694 structType.getQualifier().layoutPacking == glslang::ElpStd430;
1695
1696 // override anything in currentOffset with user-set offset
1697 if (memberType.getQualifier().hasOffset())
1698 currentOffset = memberType.getQualifier().layoutOffset;
1699
1700 // It could be that current linker usage in glslang updated all the layoutOffset,
1701 // in which case the following code does not matter. But, that's not quite right
1702 // once cross-compilation unit GLSL validation is done, as the original user
1703 // settings are needed in layoutOffset, and then the following will come into play.
1704
1705 if (! forceOffset) {
1706 if (! memberType.getQualifier().hasOffset())
1707 currentOffset = -1;
1708
1709 return;
1710 }
1711
1712 // Getting this far means we are forcing offsets
1713 if (currentOffset < 0)
1714 currentOffset = 0;
1715
1716 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1717 // but possibly not yet correctly aligned.
1718
1719 int memberSize;
1720 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, memberType.getQualifier().layoutPacking == glslang::ElpStd140);
1721 glslang::RoundToPow2(currentOffset, memberAlignment);
1722 nextOffset = currentOffset + memberSize;
1723}
1724
John Kessenich140f3df2015-06-26 16:58:36 -06001725bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1726{
1727 return node->getName() == "main(";
1728}
1729
1730// Make all the functions, skeletally, without actually visiting their bodies.
1731void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1732{
1733 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1734 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1735 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1736 continue;
1737
1738 // We're on a user function. Set up the basic interface for the function now,
1739 // so that it's available to call.
1740 // Translating the body will happen later.
1741 //
1742 // Typically (except for a "const in" parameter), an address will be passed to the
1743 // function. What it is an address of varies:
1744 //
1745 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1746 // so that write needs to be to a copy, hence the address of a copy works.
1747 //
1748 // - "const in" parameters can just be the r-value, as no writes need occur.
1749 //
1750 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1751 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1752
1753 std::vector<spv::Id> paramTypes;
1754 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1755
1756 for (int p = 0; p < (int)parameters.size(); ++p) {
1757 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1758 spv::Id typeId = convertGlslangToSpvType(paramType);
1759 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1760 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1761 else
1762 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1763 paramTypes.push_back(typeId);
1764 }
1765
1766 spv::Block* functionBlock;
1767 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1768 paramTypes, &functionBlock);
1769
1770 // Track function to emit/call later
1771 functionMap[glslFunction->getName().c_str()] = function;
1772
1773 // Set the parameter id's
1774 for (int p = 0; p < (int)parameters.size(); ++p) {
1775 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1776 // give a name too
1777 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1778 }
1779 }
1780}
1781
1782// Process all the initializers, while skipping the functions and link objects
1783void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1784{
1785 builder.setBuildPoint(shaderEntry->getLastBlock());
1786 for (int i = 0; i < (int)initializers.size(); ++i) {
1787 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1788 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1789
1790 // We're on a top-level node that's not a function. Treat as an initializer, whose
1791 // code goes into the beginning of main.
1792 initializer->traverse(this);
1793 }
1794 }
1795}
1796
1797// Process all the functions, while skipping initializers.
1798void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1799{
1800 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1801 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1802 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1803 node->traverse(this);
1804 }
1805}
1806
1807void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1808{
1809 // SPIR-V functions should already be in the functionMap from the prepass
1810 // that called makeFunctions().
1811 spv::Function* function = functionMap[node->getName().c_str()];
1812 spv::Block* functionBlock = function->getEntryBlock();
1813 builder.setBuildPoint(functionBlock);
1814}
1815
Rex Xu04db3f52015-09-16 11:44:02 +08001816void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001817{
Rex Xufc618912015-09-09 16:42:49 +08001818 const glslang::TIntermSequence& glslangArguments = node.getSequence();
John Kessenich140f3df2015-06-26 16:58:36 -06001819 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1820 builder.clearAccessChain();
1821 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001822
1823 // Special case l-value operands
1824 bool lvalue = false;
1825 switch (node.getOp()) {
1826 case glslang::EOpImageAtomicAdd:
1827 case glslang::EOpImageAtomicMin:
1828 case glslang::EOpImageAtomicMax:
1829 case glslang::EOpImageAtomicAnd:
1830 case glslang::EOpImageAtomicOr:
1831 case glslang::EOpImageAtomicXor:
1832 case glslang::EOpImageAtomicExchange:
1833 case glslang::EOpImageAtomicCompSwap:
1834 if (i == 0)
1835 lvalue = true;
1836 break;
1837 default:
1838 break;
1839 }
1840
Rex Xu6b86d492015-09-16 17:48:22 +08001841 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08001842 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08001843 else
Rex Xu30f92582015-09-14 10:38:56 +08001844 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001845 }
1846}
1847
John Kessenichfc51d282015-08-19 13:34:18 -06001848void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001849{
John Kessenichfc51d282015-08-19 13:34:18 -06001850 builder.clearAccessChain();
1851 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001852 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06001853}
John Kessenich140f3df2015-06-26 16:58:36 -06001854
John Kessenichfc51d282015-08-19 13:34:18 -06001855spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1856{
Rex Xufc618912015-09-09 16:42:49 +08001857 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06001858 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001859 }
1860
John Kessenichfc51d282015-08-19 13:34:18 -06001861 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06001862 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1863 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1864 std::vector<spv::Id> arguments;
1865 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08001866 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06001867 else
1868 translateArguments(*node->getAsUnaryNode(), arguments);
1869 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1870
1871 spv::Builder::TextureParameters params = { };
1872 params.sampler = arguments[0];
1873
Rex Xu04db3f52015-09-16 11:44:02 +08001874 glslang::TCrackedTextureOp cracked;
1875 node->crackTexture(sampler, cracked);
1876
John Kessenichfc51d282015-08-19 13:34:18 -06001877 // Check for queries
1878 if (cracked.query) {
1879 switch (node->getOp()) {
1880 case glslang::EOpImageQuerySize:
1881 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001882 if (arguments.size() > 1) {
1883 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001884 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001885 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001886 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001887 case glslang::EOpImageQuerySamples:
1888 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001889 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001890 case glslang::EOpTextureQueryLod:
1891 params.coords = arguments[1];
1892 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1893 case glslang::EOpTextureQueryLevels:
1894 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1895 default:
1896 assert(0);
1897 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001898 }
John Kessenich140f3df2015-06-26 16:58:36 -06001899 }
1900
Rex Xufc618912015-09-09 16:42:49 +08001901 // Check for image functions other than queries
1902 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06001903 std::vector<spv::Id> operands;
1904 auto opIt = arguments.begin();
1905 operands.push_back(*(opIt++));
1906 operands.push_back(*(opIt++));
1907 if (node->getOp() == glslang::EOpImageStore)
Rex Xu6b86d492015-09-16 17:48:22 +08001908 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06001909 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07001910 if (sampler.ms) {
1911 operands.push_back(spv::ImageOperandsSampleMask);
1912 operands.push_back(*(opIt++));
1913 }
John Kessenich56bab042015-09-16 10:54:31 -06001914 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
1915 } else if (node->getOp() == glslang::EOpImageStore) {
1916 builder.createNoResultOp(spv::OpImageWrite, operands);
1917 return spv::NoResult;
Rex Xu6b86d492015-09-16 17:48:22 +08001918 } else {
1919 // Process image atomic operations
1920
1921 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
1922 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich56bab042015-09-16 10:54:31 -06001923 operands.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06001924
Rex Xufc618912015-09-09 16:42:49 +08001925 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06001926 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08001927
1928 std::vector<spv::Id> operands;
1929 operands.push_back(pointer);
1930 for (; opIt != arguments.end(); ++opIt)
1931 operands.push_back(*opIt);
1932
Rex Xu04db3f52015-09-16 11:44:02 +08001933 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08001934 }
1935 }
1936
1937 // Check for texture functions other than queries
John Kessenichfc51d282015-08-19 13:34:18 -06001938
Rex Xu71519fe2015-11-11 15:35:47 +08001939 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1940
John Kessenichfc51d282015-08-19 13:34:18 -06001941 // check for bias argument
1942 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08001943 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06001944 int nonBiasArgCount = 2;
1945 if (cracked.offset)
1946 ++nonBiasArgCount;
1947 if (cracked.grad)
1948 nonBiasArgCount += 2;
1949
1950 if ((int)arguments.size() > nonBiasArgCount)
1951 bias = true;
1952 }
1953
John Kessenichfc51d282015-08-19 13:34:18 -06001954 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07001955
John Kessenichfc51d282015-08-19 13:34:18 -06001956 params.coords = arguments[1];
1957 int extraArgs = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001958
1959 // sort out where Dref is coming from
1960 if (sampler.shadow && sampler.dim == glslang::EsdCube && sampler.arrayed)
John Kessenichfc51d282015-08-19 13:34:18 -06001961 params.Dref = arguments[2];
John Kessenich55e7d112015-11-15 21:33:39 -07001962 else if (sampler.shadow && cracked.gather) {
1963 params.Dref = arguments[2];
1964 ++extraArgs;
1965 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06001966 std::vector<spv::Id> indexes;
1967 int comp;
1968 if (cracked.proj)
1969 comp = 3;
1970 else
1971 comp = builder.getNumComponents(params.coords) - 1;
1972 indexes.push_back(comp);
1973 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1974 }
1975 if (cracked.lod) {
1976 params.lod = arguments[2];
1977 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08001978 } else if (sampler.ms) {
1979 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08001980 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06001981 }
1982 if (cracked.grad) {
1983 params.gradX = arguments[2 + extraArgs];
1984 params.gradY = arguments[3 + extraArgs];
1985 extraArgs += 2;
1986 }
John Kessenich55e7d112015-11-15 21:33:39 -07001987 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06001988 params.offset = arguments[2 + extraArgs];
1989 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07001990 } else if (cracked.offsets) {
1991 params.offsets = arguments[2 + extraArgs];
1992 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06001993 }
1994 if (bias) {
1995 params.bias = arguments[2 + extraArgs];
1996 ++extraArgs;
1997 }
John Kessenich55e7d112015-11-15 21:33:39 -07001998 if (cracked.gather && ! sampler.shadow) {
1999 // default component is 0, if missing, otherwise an argument
2000 if (2 + extraArgs < (int)arguments.size()) {
2001 params.comp = arguments[2 + extraArgs];
2002 ++extraArgs;
2003 } else {
2004 params.comp = builder.makeIntConstant(0);
2005 }
2006 }
John Kessenichfc51d282015-08-19 13:34:18 -06002007
John Kessenich55e7d112015-11-15 21:33:39 -07002008 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, cracked.gather, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002009}
2010
2011spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2012{
2013 // Grab the function's pointer from the previously created function
2014 spv::Function* function = functionMap[node->getName().c_str()];
2015 if (! function)
2016 return 0;
2017
2018 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2019 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2020
2021 // See comments in makeFunctions() for details about the semantics for parameter passing.
2022 //
2023 // These imply we need a four step process:
2024 // 1. Evaluate the arguments
2025 // 2. Allocate and make copies of in, out, and inout arguments
2026 // 3. Make the call
2027 // 4. Copy back the results
2028
2029 // 1. Evaluate the arguments
2030 std::vector<spv::Builder::AccessChain> lValues;
2031 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06002032 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002033 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2034 // build l-value
2035 builder.clearAccessChain();
2036 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06002037 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002038 // keep outputs as l-values, evaluate input-only as r-values
2039 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2040 // save l-value
2041 lValues.push_back(builder.getAccessChain());
2042 } else {
2043 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06002044 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002045 }
2046 }
2047
2048 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2049 // copy the original into that space.
2050 //
2051 // Also, build up the list of actual arguments to pass in for the call
2052 int lValueCount = 0;
2053 int rValueCount = 0;
2054 std::vector<spv::Id> spvArgs;
2055 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2056 spv::Id arg;
2057 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2058 // need space to hold the copy
2059 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2060 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2061 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2062 // need to copy the input into output space
2063 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06002064 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002065 builder.createStore(copy, arg);
2066 }
2067 ++lValueCount;
2068 } else {
2069 arg = rValues[rValueCount];
2070 ++rValueCount;
2071 }
2072 spvArgs.push_back(arg);
2073 }
2074
2075 // 3. Make the call.
2076 spv::Id result = builder.createFunctionCall(function, spvArgs);
2077
2078 // 4. Copy back out an "out" arguments.
2079 lValueCount = 0;
2080 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2081 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2082 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2083 spv::Id copy = builder.createLoad(spvArgs[a]);
2084 builder.setAccessChain(lValues[lValueCount]);
2085 builder.accessChainStore(copy);
2086 }
2087 ++lValueCount;
2088 }
2089 }
2090
2091 return result;
2092}
2093
2094// Translate AST operation to SPV operation, already having SPV-based operands/types.
2095spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2096 spv::Id typeId, spv::Id left, spv::Id right,
2097 glslang::TBasicType typeProxy, bool reduceComparison)
2098{
2099 bool isUnsigned = typeProxy == glslang::EbtUint;
2100 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2101
2102 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002103 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002104 bool comparison = false;
2105
2106 switch (op) {
2107 case glslang::EOpAdd:
2108 case glslang::EOpAddAssign:
2109 if (isFloat)
2110 binOp = spv::OpFAdd;
2111 else
2112 binOp = spv::OpIAdd;
2113 break;
2114 case glslang::EOpSub:
2115 case glslang::EOpSubAssign:
2116 if (isFloat)
2117 binOp = spv::OpFSub;
2118 else
2119 binOp = spv::OpISub;
2120 break;
2121 case glslang::EOpMul:
2122 case glslang::EOpMulAssign:
2123 if (isFloat)
2124 binOp = spv::OpFMul;
2125 else
2126 binOp = spv::OpIMul;
2127 break;
2128 case glslang::EOpVectorTimesScalar:
2129 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002130 if (isFloat) {
2131 if (builder.isVector(right))
2132 std::swap(left, right);
2133 assert(builder.isScalar(right));
2134 needMatchingVectors = false;
2135 binOp = spv::OpVectorTimesScalar;
2136 } else
2137 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002138 break;
2139 case glslang::EOpVectorTimesMatrix:
2140 case glslang::EOpVectorTimesMatrixAssign:
2141 assert(builder.isVector(left));
2142 assert(builder.isMatrix(right));
2143 binOp = spv::OpVectorTimesMatrix;
2144 break;
2145 case glslang::EOpMatrixTimesVector:
2146 assert(builder.isMatrix(left));
2147 assert(builder.isVector(right));
2148 binOp = spv::OpMatrixTimesVector;
2149 break;
2150 case glslang::EOpMatrixTimesScalar:
2151 case glslang::EOpMatrixTimesScalarAssign:
2152 if (builder.isMatrix(right))
2153 std::swap(left, right);
2154 assert(builder.isScalar(right));
2155 binOp = spv::OpMatrixTimesScalar;
2156 break;
2157 case glslang::EOpMatrixTimesMatrix:
2158 case glslang::EOpMatrixTimesMatrixAssign:
2159 assert(builder.isMatrix(left));
2160 assert(builder.isMatrix(right));
2161 binOp = spv::OpMatrixTimesMatrix;
2162 break;
2163 case glslang::EOpOuterProduct:
2164 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002165 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002166 break;
2167
2168 case glslang::EOpDiv:
2169 case glslang::EOpDivAssign:
2170 if (isFloat)
2171 binOp = spv::OpFDiv;
2172 else if (isUnsigned)
2173 binOp = spv::OpUDiv;
2174 else
2175 binOp = spv::OpSDiv;
2176 break;
2177 case glslang::EOpMod:
2178 case glslang::EOpModAssign:
2179 if (isFloat)
2180 binOp = spv::OpFMod;
2181 else if (isUnsigned)
2182 binOp = spv::OpUMod;
2183 else
2184 binOp = spv::OpSMod;
2185 break;
2186 case glslang::EOpRightShift:
2187 case glslang::EOpRightShiftAssign:
2188 if (isUnsigned)
2189 binOp = spv::OpShiftRightLogical;
2190 else
2191 binOp = spv::OpShiftRightArithmetic;
2192 break;
2193 case glslang::EOpLeftShift:
2194 case glslang::EOpLeftShiftAssign:
2195 binOp = spv::OpShiftLeftLogical;
2196 break;
2197 case glslang::EOpAnd:
2198 case glslang::EOpAndAssign:
2199 binOp = spv::OpBitwiseAnd;
2200 break;
2201 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002202 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002203 binOp = spv::OpLogicalAnd;
2204 break;
2205 case glslang::EOpInclusiveOr:
2206 case glslang::EOpInclusiveOrAssign:
2207 binOp = spv::OpBitwiseOr;
2208 break;
2209 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002210 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002211 binOp = spv::OpLogicalOr;
2212 break;
2213 case glslang::EOpExclusiveOr:
2214 case glslang::EOpExclusiveOrAssign:
2215 binOp = spv::OpBitwiseXor;
2216 break;
2217 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002218 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002219 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002220 break;
2221
2222 case glslang::EOpLessThan:
2223 case glslang::EOpGreaterThan:
2224 case glslang::EOpLessThanEqual:
2225 case glslang::EOpGreaterThanEqual:
2226 case glslang::EOpEqual:
2227 case glslang::EOpNotEqual:
2228 case glslang::EOpVectorEqual:
2229 case glslang::EOpVectorNotEqual:
2230 comparison = true;
2231 break;
2232 default:
2233 break;
2234 }
2235
John Kessenich7c1aa102015-10-15 13:29:11 -06002236 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002237 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002238 assert(comparison == false);
John Kessenich140f3df2015-06-26 16:58:36 -06002239 if (builder.isMatrix(left) || builder.isMatrix(right)) {
2240 switch (binOp) {
2241 case spv::OpMatrixTimesScalar:
2242 case spv::OpVectorTimesMatrix:
2243 case spv::OpMatrixTimesVector:
2244 case spv::OpMatrixTimesMatrix:
2245 break;
2246 case spv::OpFDiv:
2247 // turn it into a multiply...
2248 assert(builder.isMatrix(left) && builder.isScalar(right));
2249 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2250 binOp = spv::OpFMul;
2251 break;
2252 default:
2253 spv::MissingFunctionality("binary operation on matrix");
2254 break;
2255 }
2256
2257 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2258 builder.setPrecision(id, precision);
2259
2260 return id;
2261 }
2262
2263 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002264 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002265 builder.promoteScalar(precision, left, right);
2266
2267 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2268 builder.setPrecision(id, precision);
2269
2270 return id;
2271 }
2272
2273 if (! comparison)
2274 return 0;
2275
John Kessenich7c1aa102015-10-15 13:29:11 -06002276 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002277
2278 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2279 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2280
2281 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
2282 }
2283
2284 switch (op) {
2285 case glslang::EOpLessThan:
2286 if (isFloat)
2287 binOp = spv::OpFOrdLessThan;
2288 else if (isUnsigned)
2289 binOp = spv::OpULessThan;
2290 else
2291 binOp = spv::OpSLessThan;
2292 break;
2293 case glslang::EOpGreaterThan:
2294 if (isFloat)
2295 binOp = spv::OpFOrdGreaterThan;
2296 else if (isUnsigned)
2297 binOp = spv::OpUGreaterThan;
2298 else
2299 binOp = spv::OpSGreaterThan;
2300 break;
2301 case glslang::EOpLessThanEqual:
2302 if (isFloat)
2303 binOp = spv::OpFOrdLessThanEqual;
2304 else if (isUnsigned)
2305 binOp = spv::OpULessThanEqual;
2306 else
2307 binOp = spv::OpSLessThanEqual;
2308 break;
2309 case glslang::EOpGreaterThanEqual:
2310 if (isFloat)
2311 binOp = spv::OpFOrdGreaterThanEqual;
2312 else if (isUnsigned)
2313 binOp = spv::OpUGreaterThanEqual;
2314 else
2315 binOp = spv::OpSGreaterThanEqual;
2316 break;
2317 case glslang::EOpEqual:
2318 case glslang::EOpVectorEqual:
2319 if (isFloat)
2320 binOp = spv::OpFOrdEqual;
2321 else
2322 binOp = spv::OpIEqual;
2323 break;
2324 case glslang::EOpNotEqual:
2325 case glslang::EOpVectorNotEqual:
2326 if (isFloat)
2327 binOp = spv::OpFOrdNotEqual;
2328 else
2329 binOp = spv::OpINotEqual;
2330 break;
2331 default:
2332 break;
2333 }
2334
2335 if (binOp != spv::OpNop) {
2336 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2337 builder.setPrecision(id, precision);
2338
2339 return id;
2340 }
2341
2342 return 0;
2343}
2344
Rex Xu04db3f52015-09-16 11:44:02 +08002345spv::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 -06002346{
2347 spv::Op unaryOp = spv::OpNop;
2348 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002349 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002350 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002351
2352 switch (op) {
2353 case glslang::EOpNegative:
2354 if (isFloat)
2355 unaryOp = spv::OpFNegate;
2356 else
2357 unaryOp = spv::OpSNegate;
2358 break;
2359
2360 case glslang::EOpLogicalNot:
2361 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002362 unaryOp = spv::OpLogicalNot;
2363 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002364 case glslang::EOpBitwiseNot:
2365 unaryOp = spv::OpNot;
2366 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002367
John Kessenich140f3df2015-06-26 16:58:36 -06002368 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002369 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002370 break;
2371 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002372 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002373 break;
2374 case glslang::EOpTranspose:
2375 unaryOp = spv::OpTranspose;
2376 break;
2377
2378 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002379 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002380 break;
2381 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002382 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002383 break;
2384 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002385 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002386 break;
2387 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002388 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002389 break;
2390 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002391 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002392 break;
2393 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002394 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002395 break;
2396 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002397 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002398 break;
2399 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002400 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002401 break;
2402
2403 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002404 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002405 break;
2406 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002407 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002408 break;
2409 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002410 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002411 break;
2412 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002413 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002414 break;
2415 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002416 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002417 break;
2418 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002419 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002420 break;
2421
2422 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002423 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002424 break;
2425 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002426 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002427 break;
2428
2429 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002430 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002431 break;
2432 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002433 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002434 break;
2435 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002436 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002437 break;
2438 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002439 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002440 break;
2441 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002442 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002443 break;
2444 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002445 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002446 break;
2447
2448 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002449 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002450 break;
2451 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002452 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002453 break;
2454 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002455 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002456 break;
2457 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002458 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002459 break;
2460 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002461 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002462 break;
2463 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002464 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002465 break;
2466
2467 case glslang::EOpIsNan:
2468 unaryOp = spv::OpIsNan;
2469 break;
2470 case glslang::EOpIsInf:
2471 unaryOp = spv::OpIsInf;
2472 break;
2473
John Kessenich140f3df2015-06-26 16:58:36 -06002474 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002475 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002476 break;
2477 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002478 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002479 break;
2480 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002481 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002482 break;
2483 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002484 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002485 break;
2486 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002487 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002488 break;
2489 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002490 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002491 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002492 case glslang::EOpPackSnorm4x8:
2493 libCall = spv::GLSLstd450PackSnorm4x8;
2494 break;
2495 case glslang::EOpUnpackSnorm4x8:
2496 libCall = spv::GLSLstd450UnpackSnorm4x8;
2497 break;
2498 case glslang::EOpPackUnorm4x8:
2499 libCall = spv::GLSLstd450PackUnorm4x8;
2500 break;
2501 case glslang::EOpUnpackUnorm4x8:
2502 libCall = spv::GLSLstd450UnpackUnorm4x8;
2503 break;
2504 case glslang::EOpPackDouble2x32:
2505 libCall = spv::GLSLstd450PackDouble2x32;
2506 break;
2507 case glslang::EOpUnpackDouble2x32:
2508 libCall = spv::GLSLstd450UnpackDouble2x32;
2509 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002510
2511 case glslang::EOpDPdx:
2512 unaryOp = spv::OpDPdx;
2513 break;
2514 case glslang::EOpDPdy:
2515 unaryOp = spv::OpDPdy;
2516 break;
2517 case glslang::EOpFwidth:
2518 unaryOp = spv::OpFwidth;
2519 break;
2520 case glslang::EOpDPdxFine:
2521 unaryOp = spv::OpDPdxFine;
2522 break;
2523 case glslang::EOpDPdyFine:
2524 unaryOp = spv::OpDPdyFine;
2525 break;
2526 case glslang::EOpFwidthFine:
2527 unaryOp = spv::OpFwidthFine;
2528 break;
2529 case glslang::EOpDPdxCoarse:
2530 unaryOp = spv::OpDPdxCoarse;
2531 break;
2532 case glslang::EOpDPdyCoarse:
2533 unaryOp = spv::OpDPdyCoarse;
2534 break;
2535 case glslang::EOpFwidthCoarse:
2536 unaryOp = spv::OpFwidthCoarse;
2537 break;
2538
2539 case glslang::EOpAny:
2540 unaryOp = spv::OpAny;
2541 break;
2542 case glslang::EOpAll:
2543 unaryOp = spv::OpAll;
2544 break;
2545
2546 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002547 if (isFloat)
2548 libCall = spv::GLSLstd450FAbs;
2549 else
2550 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002551 break;
2552 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002553 if (isFloat)
2554 libCall = spv::GLSLstd450FSign;
2555 else
2556 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002557 break;
2558
John Kessenichfc51d282015-08-19 13:34:18 -06002559 case glslang::EOpAtomicCounterIncrement:
2560 case glslang::EOpAtomicCounterDecrement:
2561 case glslang::EOpAtomicCounter:
2562 {
2563 // Handle all of the atomics in one place, in createAtomicOperation()
2564 std::vector<spv::Id> operands;
2565 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002566 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002567 }
2568
2569 case glslang::EOpImageLoad:
2570 unaryOp = spv::OpImageRead;
2571 break;
2572
2573 case glslang::EOpBitFieldReverse:
2574 unaryOp = spv::OpBitReverse;
2575 break;
2576 case glslang::EOpBitCount:
2577 unaryOp = spv::OpBitCount;
2578 break;
2579 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002580 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002581 break;
2582 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002583 if (isUnsigned)
2584 libCall = spv::GLSLstd450FindUMsb;
2585 else
2586 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002587 break;
2588
John Kessenich140f3df2015-06-26 16:58:36 -06002589 default:
2590 return 0;
2591 }
2592
2593 spv::Id id;
2594 if (libCall >= 0) {
2595 std::vector<spv::Id> args;
2596 args.push_back(operand);
2597 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2598 } else
2599 id = builder.createUnaryOp(unaryOp, typeId, operand);
2600
2601 builder.setPrecision(id, precision);
2602
2603 return id;
2604}
2605
2606spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2607{
2608 spv::Op convOp = spv::OpNop;
2609 spv::Id zero = 0;
2610 spv::Id one = 0;
2611
2612 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2613
2614 switch (op) {
2615 case glslang::EOpConvIntToBool:
2616 case glslang::EOpConvUintToBool:
2617 zero = builder.makeUintConstant(0);
2618 zero = makeSmearedConstant(zero, vectorSize);
2619 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2620
2621 case glslang::EOpConvFloatToBool:
2622 zero = builder.makeFloatConstant(0.0F);
2623 zero = makeSmearedConstant(zero, vectorSize);
2624 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2625
2626 case glslang::EOpConvDoubleToBool:
2627 zero = builder.makeDoubleConstant(0.0);
2628 zero = makeSmearedConstant(zero, vectorSize);
2629 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2630
2631 case glslang::EOpConvBoolToFloat:
2632 convOp = spv::OpSelect;
2633 zero = builder.makeFloatConstant(0.0);
2634 one = builder.makeFloatConstant(1.0);
2635 break;
2636 case glslang::EOpConvBoolToDouble:
2637 convOp = spv::OpSelect;
2638 zero = builder.makeDoubleConstant(0.0);
2639 one = builder.makeDoubleConstant(1.0);
2640 break;
2641 case glslang::EOpConvBoolToInt:
2642 zero = builder.makeIntConstant(0);
2643 one = builder.makeIntConstant(1);
2644 convOp = spv::OpSelect;
2645 break;
2646 case glslang::EOpConvBoolToUint:
2647 zero = builder.makeUintConstant(0);
2648 one = builder.makeUintConstant(1);
2649 convOp = spv::OpSelect;
2650 break;
2651
2652 case glslang::EOpConvIntToFloat:
2653 case glslang::EOpConvIntToDouble:
2654 convOp = spv::OpConvertSToF;
2655 break;
2656
2657 case glslang::EOpConvUintToFloat:
2658 case glslang::EOpConvUintToDouble:
2659 convOp = spv::OpConvertUToF;
2660 break;
2661
2662 case glslang::EOpConvDoubleToFloat:
2663 case glslang::EOpConvFloatToDouble:
2664 convOp = spv::OpFConvert;
2665 break;
2666
2667 case glslang::EOpConvFloatToInt:
2668 case glslang::EOpConvDoubleToInt:
2669 convOp = spv::OpConvertFToS;
2670 break;
2671
2672 case glslang::EOpConvUintToInt:
2673 case glslang::EOpConvIntToUint:
2674 convOp = spv::OpBitcast;
2675 break;
2676
2677 case glslang::EOpConvFloatToUint:
2678 case glslang::EOpConvDoubleToUint:
2679 convOp = spv::OpConvertFToU;
2680 break;
2681 default:
2682 break;
2683 }
2684
2685 spv::Id result = 0;
2686 if (convOp == spv::OpNop)
2687 return result;
2688
2689 if (convOp == spv::OpSelect) {
2690 zero = makeSmearedConstant(zero, vectorSize);
2691 one = makeSmearedConstant(one, vectorSize);
2692 result = builder.createTriOp(convOp, destType, operand, one, zero);
2693 } else
2694 result = builder.createUnaryOp(convOp, destType, operand);
2695
2696 builder.setPrecision(result, precision);
2697
2698 return result;
2699}
2700
2701spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2702{
2703 if (vectorSize == 0)
2704 return constant;
2705
2706 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2707 std::vector<spv::Id> components;
2708 for (int c = 0; c < vectorSize; ++c)
2709 components.push_back(constant);
2710 return builder.makeCompositeConstant(vectorTypeId, components);
2711}
2712
John Kessenich426394d2015-07-23 10:22:48 -06002713// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08002714spv::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 -06002715{
2716 spv::Op opCode = spv::OpNop;
2717
2718 switch (op) {
2719 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08002720 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06002721 opCode = spv::OpAtomicIAdd;
2722 break;
2723 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08002724 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08002725 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002726 break;
2727 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08002728 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08002729 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002730 break;
2731 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08002732 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06002733 opCode = spv::OpAtomicAnd;
2734 break;
2735 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08002736 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06002737 opCode = spv::OpAtomicOr;
2738 break;
2739 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08002740 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06002741 opCode = spv::OpAtomicXor;
2742 break;
2743 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08002744 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06002745 opCode = spv::OpAtomicExchange;
2746 break;
2747 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08002748 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06002749 opCode = spv::OpAtomicCompareExchange;
2750 break;
2751 case glslang::EOpAtomicCounterIncrement:
2752 opCode = spv::OpAtomicIIncrement;
2753 break;
2754 case glslang::EOpAtomicCounterDecrement:
2755 opCode = spv::OpAtomicIDecrement;
2756 break;
2757 case glslang::EOpAtomicCounter:
2758 opCode = spv::OpAtomicLoad;
2759 break;
2760 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002761 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06002762 break;
2763 }
2764
2765 // Sort out the operands
2766 // - mapping from glslang -> SPV
2767 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06002768 // - compare-exchange swaps the value and comparator
2769 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06002770 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2771 auto opIt = operands.begin(); // walk the glslang operands
2772 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08002773 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2774 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
2775 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08002776 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
2777 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08002778 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06002779 spvAtomicOperands.push_back(*(opIt + 1));
2780 spvAtomicOperands.push_back(*opIt);
2781 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08002782 }
John Kessenich426394d2015-07-23 10:22:48 -06002783
John Kessenich3e60a6f2015-09-14 22:45:16 -06002784 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06002785 for (; opIt != operands.end(); ++opIt)
2786 spvAtomicOperands.push_back(*opIt);
2787
2788 return builder.createOp(opCode, typeId, spvAtomicOperands);
2789}
2790
John Kessenich5e4b1242015-08-06 22:53:06 -06002791spv::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 -06002792{
John Kessenich5e4b1242015-08-06 22:53:06 -06002793 bool isUnsigned = typeProxy == glslang::EbtUint;
2794 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2795
John Kessenich140f3df2015-06-26 16:58:36 -06002796 spv::Op opCode = spv::OpNop;
2797 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002798 int consumedOperands = operands.size();
2799 spv::Id typeId0 = 0;
2800 if (consumedOperands > 0)
2801 typeId0 = builder.getTypeId(operands[0]);
2802 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002803
2804 switch (op) {
2805 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002806 if (isFloat)
2807 libCall = spv::GLSLstd450FMin;
2808 else if (isUnsigned)
2809 libCall = spv::GLSLstd450UMin;
2810 else
2811 libCall = spv::GLSLstd450SMin;
John Kessenich140f3df2015-06-26 16:58:36 -06002812 break;
2813 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002814 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002815 break;
2816 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002817 if (isFloat)
2818 libCall = spv::GLSLstd450FMax;
2819 else if (isUnsigned)
2820 libCall = spv::GLSLstd450UMax;
2821 else
2822 libCall = spv::GLSLstd450SMax;
John Kessenich140f3df2015-06-26 16:58:36 -06002823 break;
2824 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002825 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002826 break;
2827 case glslang::EOpDot:
2828 opCode = spv::OpDot;
2829 break;
2830 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002831 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002832 break;
2833
2834 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002835 if (isFloat)
2836 libCall = spv::GLSLstd450FClamp;
2837 else if (isUnsigned)
2838 libCall = spv::GLSLstd450UClamp;
2839 else
2840 libCall = spv::GLSLstd450SClamp;
John Kessenich140f3df2015-06-26 16:58:36 -06002841 break;
2842 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07002843 if (isFloat)
2844 libCall = spv::GLSLstd450FMix;
2845 else
2846 libCall = spv::GLSLstd450IMix;
John Kessenich140f3df2015-06-26 16:58:36 -06002847 break;
2848 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002849 libCall = spv::GLSLstd450Step;
John Kessenich140f3df2015-06-26 16:58:36 -06002850 break;
2851 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002852 libCall = spv::GLSLstd450SmoothStep;
John Kessenich140f3df2015-06-26 16:58:36 -06002853 break;
2854
2855 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002856 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002857 break;
2858 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002859 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002860 break;
2861 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002862 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002863 break;
2864 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002865 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002866 break;
2867 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002868 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002869 break;
John Kessenich426394d2015-07-23 10:22:48 -06002870
John Kessenich55e7d112015-11-15 21:33:39 -07002871 case glslang::EOpAddCarry:
2872 opCode = spv::OpIAddCarry;
2873 typeId = builder.makeStructResultType(typeId0, typeId0);
2874 consumedOperands = 2;
2875 break;
2876 case glslang::EOpSubBorrow:
2877 opCode = spv::OpISubBorrow;
2878 typeId = builder.makeStructResultType(typeId0, typeId0);
2879 consumedOperands = 2;
2880 break;
2881 case glslang::EOpUMulExtended:
2882 opCode = spv::OpUMulExtended;
2883 typeId = builder.makeStructResultType(typeId0, typeId0);
2884 consumedOperands = 2;
2885 break;
2886 case glslang::EOpIMulExtended:
2887 opCode = spv::OpSMulExtended;
2888 typeId = builder.makeStructResultType(typeId0, typeId0);
2889 consumedOperands = 2;
2890 break;
2891 case glslang::EOpBitfieldExtract:
2892 if (isUnsigned)
2893 opCode = spv::OpBitFieldUExtract;
2894 else
2895 opCode = spv::OpBitFieldSExtract;
2896 break;
2897 case glslang::EOpBitfieldInsert:
2898 opCode = spv::OpBitFieldInsert;
2899 break;
2900
2901 case glslang::EOpFma:
2902 libCall = spv::GLSLstd450Fma;
2903 break;
2904 case glslang::EOpFrexp:
2905 libCall = spv::GLSLstd450FrexpStruct;
2906 if (builder.getNumComponents(operands[0]) == 1)
2907 frexpIntType = builder.makeIntegerType(32, true);
2908 else
2909 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
2910 typeId = builder.makeStructResultType(typeId0, frexpIntType);
2911 consumedOperands = 1;
2912 break;
2913 case glslang::EOpLdexp:
2914 libCall = spv::GLSLstd450Ldexp;
2915 break;
2916
John Kessenich140f3df2015-06-26 16:58:36 -06002917 default:
2918 return 0;
2919 }
2920
2921 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07002922 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05002923 // Use an extended instruction from the standard library.
2924 // Construct the call arguments, without modifying the original operands vector.
2925 // We might need the remaining arguments, e.g. in the EOpFrexp case.
2926 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
2927 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07002928 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07002929 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06002930 case 0:
2931 // should all be handled by visitAggregate and createNoArgOperation
2932 assert(0);
2933 return 0;
2934 case 1:
2935 // should all be handled by createUnaryOperation
2936 assert(0);
2937 return 0;
2938 case 2:
2939 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
2940 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002941 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002942 // anything 3 or over doesn't have l-value operands, so all should be consumed
2943 assert(consumedOperands == operands.size());
2944 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06002945 break;
2946 }
2947 }
2948
John Kessenich55e7d112015-11-15 21:33:39 -07002949 // Decode the return types that were structures
2950 switch (op) {
2951 case glslang::EOpAddCarry:
2952 case glslang::EOpSubBorrow:
2953 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
2954 id = builder.createCompositeExtract(id, typeId0, 0);
2955 break;
2956 case glslang::EOpUMulExtended:
2957 case glslang::EOpIMulExtended:
2958 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
2959 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
2960 break;
2961 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05002962 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07002963 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
2964 id = builder.createCompositeExtract(id, typeId0, 0);
2965 break;
2966 default:
2967 break;
2968 }
2969
John Kessenich140f3df2015-06-26 16:58:36 -06002970 builder.setPrecision(id, precision);
2971
2972 return id;
2973}
2974
2975// Intrinsics with no arguments, no return value, and no precision.
2976spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
2977{
2978 // TODO: get the barrier operands correct
2979
2980 switch (op) {
2981 case glslang::EOpEmitVertex:
2982 builder.createNoResultOp(spv::OpEmitVertex);
2983 return 0;
2984 case glslang::EOpEndPrimitive:
2985 builder.createNoResultOp(spv::OpEndPrimitive);
2986 return 0;
2987 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002988 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
2989 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06002990 return 0;
2991 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002992 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06002993 return 0;
2994 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06002995 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002996 return 0;
2997 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06002998 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002999 return 0;
3000 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003001 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003002 return 0;
3003 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003004 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003005 return 0;
3006 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003007 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003008 return 0;
3009 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003010 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003011 return 0;
3012 }
3013}
3014
3015spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3016{
John Kessenich2f273362015-07-18 22:34:27 -06003017 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003018 spv::Id id;
3019 if (symbolValues.end() != iter) {
3020 id = iter->second;
3021 return id;
3022 }
3023
3024 // it was not found, create it
3025 id = createSpvVariable(symbol);
3026 symbolValues[symbol->getId()] = id;
3027
3028 if (! symbol->getType().isStruct()) {
3029 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
3030 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
3031 if (symbol->getQualifier().hasLocation())
3032 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3033 if (symbol->getQualifier().hasIndex())
3034 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3035 if (symbol->getQualifier().hasComponent())
3036 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3037 if (glslangIntermediate->getXfbMode()) {
3038 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003039 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003040 if (symbol->getQualifier().hasXfbBuffer())
3041 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3042 if (symbol->getQualifier().hasXfbOffset())
3043 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3044 }
3045 }
3046
3047 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
3048 if (symbol->getQualifier().hasStream())
3049 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
3050 if (symbol->getQualifier().hasSet())
3051 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3052 if (symbol->getQualifier().hasBinding())
3053 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3054 if (glslangIntermediate->getXfbMode()) {
3055 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003056 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003057 if (symbol->getQualifier().hasXfbBuffer())
3058 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3059 }
3060
3061 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003062 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003063 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06003064 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003065
John Kessenich140f3df2015-06-26 16:58:36 -06003066 return id;
3067}
3068
John Kessenich55e7d112015-11-15 21:33:39 -07003069// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003070void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3071{
3072 if (dec != spv::BadValue)
3073 builder.addDecoration(id, dec);
3074}
3075
John Kessenich55e7d112015-11-15 21:33:39 -07003076// If 'dec' is valid, add a one-operand decoration to an object
3077void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3078{
3079 if (dec != spv::BadValue)
3080 builder.addDecoration(id, dec, value);
3081}
3082
3083// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003084void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3085{
3086 if (dec != spv::BadValue)
3087 builder.addMemberDecoration(id, (unsigned)member, dec);
3088}
3089
John Kessenich55e7d112015-11-15 21:33:39 -07003090// Make a full tree of instructions to build a SPIR-V specialization constant,
3091// or regularly constant if possible.
3092//
3093// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3094//
3095// Recursively walk the nodes. The nodes form a tree whose leaves are
3096// regular constants, which themselves are trees that createSpvConstant()
3097// recursively walks. So, this function walks the "top" of the tree:
3098// - emit specialization constant-building instructions for specConstant
3099// - when running into a non-spec-constant, switch to createSpvConstant()
3100spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3101{
3102 assert(node.getQualifier().storage == glslang::EvqConst);
3103
3104 // hand off to the non-spec-constant path
3105 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3106 int nextConst = 0;
3107 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3108}
3109
John Kessenich140f3df2015-06-26 16:58:36 -06003110// Use 'consts' as the flattened glslang source of scalar constants to recursively
3111// build the aggregate SPIR-V constant.
3112//
3113// If there are not enough elements present in 'consts', 0 will be substituted;
3114// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3115//
John Kessenich55e7d112015-11-15 21:33:39 -07003116spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003117{
3118 // vector of constants for SPIR-V
3119 std::vector<spv::Id> spvConsts;
3120
3121 // Type is used for struct and array constants
3122 spv::Id typeId = convertGlslangToSpvType(glslangType);
3123
3124 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003125 glslang::TType elementType(glslangType, 0);
3126 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003127 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003128 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003129 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003130 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003131 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003132 } else if (glslangType.getStruct()) {
3133 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3134 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003135 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003136 } else if (glslangType.isVector()) {
3137 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3138 bool zero = nextConst >= consts.size();
3139 switch (glslangType.getBasicType()) {
3140 case glslang::EbtInt:
3141 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3142 break;
3143 case glslang::EbtUint:
3144 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3145 break;
3146 case glslang::EbtFloat:
3147 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3148 break;
3149 case glslang::EbtDouble:
3150 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3151 break;
3152 case glslang::EbtBool:
3153 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3154 break;
3155 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003156 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003157 break;
3158 }
3159 ++nextConst;
3160 }
3161 } else {
3162 // we have a non-aggregate (scalar) constant
3163 bool zero = nextConst >= consts.size();
3164 spv::Id scalar = 0;
3165 switch (glslangType.getBasicType()) {
3166 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003167 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003168 break;
3169 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003170 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003171 break;
3172 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003173 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003174 break;
3175 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003176 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003177 break;
3178 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003179 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003180 break;
3181 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003182 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003183 break;
3184 }
3185 ++nextConst;
3186 return scalar;
3187 }
3188
3189 return builder.makeCompositeConstant(typeId, spvConsts);
3190}
3191
John Kessenich7c1aa102015-10-15 13:29:11 -06003192// Return true if the node is a constant or symbol whose reading has no
3193// non-trivial observable cost or effect.
3194bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3195{
3196 // don't know what this is
3197 if (node == nullptr)
3198 return false;
3199
3200 // a constant is safe
3201 if (node->getAsConstantUnion() != nullptr)
3202 return true;
3203
3204 // not a symbol means non-trivial
3205 if (node->getAsSymbolNode() == nullptr)
3206 return false;
3207
3208 // a symbol, depends on what's being read
3209 switch (node->getType().getQualifier().storage) {
3210 case glslang::EvqTemporary:
3211 case glslang::EvqGlobal:
3212 case glslang::EvqIn:
3213 case glslang::EvqInOut:
3214 case glslang::EvqConst:
3215 case glslang::EvqConstReadOnly:
3216 case glslang::EvqUniform:
3217 return true;
3218 default:
3219 return false;
3220 }
3221}
3222
3223// A node is trivial if it is a single operation with no side effects.
3224// Error on the side of saying non-trivial.
3225// Return true if trivial.
3226bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3227{
3228 if (node == nullptr)
3229 return false;
3230
3231 // symbols and constants are trivial
3232 if (isTrivialLeaf(node))
3233 return true;
3234
3235 // otherwise, it needs to be a simple operation or one or two leaf nodes
3236
3237 // not a simple operation
3238 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3239 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3240 if (binaryNode == nullptr && unaryNode == nullptr)
3241 return false;
3242
3243 // not on leaf nodes
3244 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3245 return false;
3246
3247 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3248 return false;
3249 }
3250
3251 switch (node->getAsOperator()->getOp()) {
3252 case glslang::EOpLogicalNot:
3253 case glslang::EOpConvIntToBool:
3254 case glslang::EOpConvUintToBool:
3255 case glslang::EOpConvFloatToBool:
3256 case glslang::EOpConvDoubleToBool:
3257 case glslang::EOpEqual:
3258 case glslang::EOpNotEqual:
3259 case glslang::EOpLessThan:
3260 case glslang::EOpGreaterThan:
3261 case glslang::EOpLessThanEqual:
3262 case glslang::EOpGreaterThanEqual:
3263 case glslang::EOpIndexDirect:
3264 case glslang::EOpIndexDirectStruct:
3265 case glslang::EOpLogicalXor:
3266 case glslang::EOpAny:
3267 case glslang::EOpAll:
3268 return true;
3269 default:
3270 return false;
3271 }
3272}
3273
3274// Emit short-circuiting code, where 'right' is never evaluated unless
3275// the left side is true (for &&) or false (for ||).
3276spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3277{
3278 spv::Id boolTypeId = builder.makeBoolType();
3279
3280 // emit left operand
3281 builder.clearAccessChain();
3282 left.traverse(this);
3283 spv::Id leftId = builder.accessChainLoad(boolTypeId);
3284
3285 // Operands to accumulate OpPhi operands
3286 std::vector<spv::Id> phiOperands;
3287 // accumulate left operand's phi information
3288 phiOperands.push_back(leftId);
3289 phiOperands.push_back(builder.getBuildPoint()->getId());
3290
3291 // Make the two kinds of operation symmetric with a "!"
3292 // || => emit "if (! left) result = right"
3293 // && => emit "if ( left) result = right"
3294 //
3295 // TODO: this runtime "not" for || could be avoided by adding functionality
3296 // to 'builder' to have an "else" without an "then"
3297 if (op == glslang::EOpLogicalOr)
3298 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3299
3300 // make an "if" based on the left value
3301 spv::Builder::If ifBuilder(leftId, builder);
3302
3303 // emit right operand as the "then" part of the "if"
3304 builder.clearAccessChain();
3305 right.traverse(this);
3306 spv::Id rightId = builder.accessChainLoad(boolTypeId);
3307
3308 // accumulate left operand's phi information
3309 phiOperands.push_back(rightId);
3310 phiOperands.push_back(builder.getBuildPoint()->getId());
3311
3312 // finish the "if"
3313 ifBuilder.makeEndIf();
3314
3315 // phi together the two results
3316 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3317}
3318
John Kessenich140f3df2015-06-26 16:58:36 -06003319}; // end anonymous namespace
3320
3321namespace glslang {
3322
John Kessenich68d78fd2015-07-12 19:28:10 -06003323void GetSpirvVersion(std::string& version)
3324{
John Kessenich9e55f632015-07-15 10:03:39 -06003325 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003326 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003327 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003328 version = buf;
3329}
3330
John Kessenich140f3df2015-06-26 16:58:36 -06003331// Write SPIR-V out to a binary file
3332void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3333{
3334 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003335 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003336 for (int i = 0; i < (int)spirv.size(); ++i) {
3337 unsigned int word = spirv[i];
3338 out.write((const char*)&word, 4);
3339 }
3340 out.close();
3341}
3342
3343//
3344// Set up the glslang traversal
3345//
3346void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3347{
3348 TIntermNode* root = intermediate.getTreeRoot();
3349
3350 if (root == 0)
3351 return;
3352
3353 glslang::GetThreadPoolAllocator().push();
3354
3355 TGlslangToSpvTraverser it(&intermediate);
3356
3357 root->traverse(&it);
3358
3359 it.dumpSpv(spirv);
3360
3361 glslang::GetThreadPoolAllocator().pop();
3362}
3363
3364}; // end namespace glslang