blob: 86e6ac3a8c186288d3d491fa8a0354c4f4d2a3ed [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
63const int GlslangMagic = 0x51a;
64
65//
66// The main holder of information for translating glslang to SPIR-V.
67//
68// Derives from the AST walking base class.
69//
70class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
71public:
72 TGlslangToSpvTraverser(const glslang::TIntermediate*);
73 virtual ~TGlslangToSpvTraverser();
74
75 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
76 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
77 void visitConstantUnion(glslang::TIntermConstantUnion*);
78 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
79 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
80 void visitSymbol(glslang::TIntermSymbol* symbol);
81 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
82 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
83 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
84
85 void dumpSpv(std::vector<unsigned int>& out) { builder.dump(out); }
86
87protected:
88 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
89 spv::Id getSampledType(const glslang::TSampler&);
90 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenich31ed4832015-09-09 17:51:38 -060091 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout);
92 bool requiresExplicitLayout(const glslang::TType& type) const;
Jason Ekstrand54aedf12015-09-05 09:50:58 -070093 int getArrayStride(const glslang::TType& arrayType);
94 int getMatrixStride(const glslang::TType& matrixType);
John Kessenich5e4b1242015-08-06 22:53:06 -060095 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset);
John Kessenich140f3df2015-06-26 16:58:36 -060096
97 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
98 void makeFunctions(const glslang::TIntermSequence&);
99 void makeGlobalInitializers(const glslang::TIntermSequence&);
100 void visitFunctions(const glslang::TIntermSequence&);
101 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800102 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600103 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
104 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600105 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
106
107 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 +0800108 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 -0600109 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
110 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800111 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 -0600112 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 -0600113 spv::Id createNoArgOperation(glslang::TOperator op);
114 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
115 void addDecoration(spv::Id id, spv::Decoration dec);
116 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
117 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst);
118
119 spv::Function* shaderEntry;
120 int sequenceDepth;
121
122 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
123 spv::Builder builder;
124 bool inMain;
125 bool mainTerminated;
126 bool linkageOnly;
127 const glslang::TIntermediate* glslangIntermediate;
128 spv::Id stdBuiltins;
129
John Kessenich2f273362015-07-18 22:34:27 -0600130 std::unordered_map<int, spv::Id> symbolValues;
131 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
132 std::unordered_map<std::string, spv::Function*> functionMap;
133 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap;
134 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 -0600135 std::stack<bool> breakForLoop; // false means break for switch
136 std::stack<glslang::TIntermTyped*> loopTerminal; // code from the last part of a for loop: for(...; ...; terminal), needed for e.g., continue };
137};
138
139//
140// Helper functions for translating glslang representations to SPIR-V enumerants.
141//
142
143// Translate glslang profile to SPIR-V source language.
144spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
145{
146 switch (profile) {
147 case ENoProfile:
148 case ECoreProfile:
149 case ECompatibilityProfile:
150 return spv::SourceLanguageGLSL;
151 case EEsProfile:
152 return spv::SourceLanguageESSL;
153 default:
154 return spv::SourceLanguageUnknown;
155 }
156}
157
158// Translate glslang language (stage) to SPIR-V execution model.
159spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
160{
161 switch (stage) {
162 case EShLangVertex: return spv::ExecutionModelVertex;
163 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
164 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
165 case EShLangGeometry: return spv::ExecutionModelGeometry;
166 case EShLangFragment: return spv::ExecutionModelFragment;
167 case EShLangCompute: return spv::ExecutionModelGLCompute;
168 default:
169 spv::MissingFunctionality("GLSL stage");
170 return spv::ExecutionModelFragment;
171 }
172}
173
174// Translate glslang type to SPIR-V storage class.
175spv::StorageClass TranslateStorageClass(const glslang::TType& type)
176{
177 if (type.getQualifier().isPipeInput())
178 return spv::StorageClassInput;
179 else if (type.getQualifier().isPipeOutput())
180 return spv::StorageClassOutput;
181 else if (type.getQualifier().isUniformOrBuffer()) {
182 if (type.getBasicType() == glslang::EbtBlock)
183 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800184 else if (type.getBasicType() == glslang::EbtAtomicUint)
185 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600186 else
187 return spv::StorageClassUniformConstant;
188 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
189 } else {
190 switch (type.getQualifier().storage) {
191 case glslang::EvqShared: return spv::StorageClassWorkgroupLocal; break;
192 case glslang::EvqGlobal: return spv::StorageClassPrivateGlobal;
193 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
194 case glslang::EvqTemporary: return spv::StorageClassFunction;
195 default:
196 spv::MissingFunctionality("unknown glslang storage class");
197 return spv::StorageClassFunction;
198 }
199 }
200}
201
202// Translate glslang sampler type to SPIR-V dimensionality.
203spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
204{
205 switch (sampler.dim) {
206 case glslang::Esd1D: return spv::Dim1D;
207 case glslang::Esd2D: return spv::Dim2D;
208 case glslang::Esd3D: return spv::Dim3D;
209 case glslang::EsdCube: return spv::DimCube;
210 case glslang::EsdRect: return spv::DimRect;
211 case glslang::EsdBuffer: return spv::DimBuffer;
212 default:
213 spv::MissingFunctionality("unknown sampler dimension");
214 return spv::Dim2D;
215 }
216}
217
218// Translate glslang type to SPIR-V precision decorations.
219spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
220{
221 switch (type.getQualifier().precision) {
John Kessenich5e4b1242015-08-06 22:53:06 -0600222 case glslang::EpqLow: return spv::DecorationRelaxedPrecision; // TODO: Map instead to 16-bit types?
223 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
224 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600225 default:
226 return spv::NoPrecision;
227 }
228}
229
230// Translate glslang type to SPIR-V block decorations.
231spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
232{
233 if (type.getBasicType() == glslang::EbtBlock) {
234 switch (type.getQualifier().storage) {
235 case glslang::EvqUniform: return spv::DecorationBlock;
236 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
237 case glslang::EvqVaryingIn: return spv::DecorationBlock;
238 case glslang::EvqVaryingOut: return spv::DecorationBlock;
239 default:
240 spv::MissingFunctionality("kind of block");
241 break;
242 }
243 }
244
245 return (spv::Decoration)spv::BadValue;
246}
247
248// Translate glslang type to SPIR-V layout decorations.
249spv::Decoration TranslateLayoutDecoration(const glslang::TType& type)
250{
251 if (type.isMatrix()) {
252 switch (type.getQualifier().layoutMatrix) {
253 case glslang::ElmRowMajor:
254 return spv::DecorationRowMajor;
255 default:
256 return spv::DecorationColMajor;
257 }
258 } else {
259 switch (type.getBasicType()) {
260 default:
261 return (spv::Decoration)spv::BadValue;
262 break;
263 case glslang::EbtBlock:
264 switch (type.getQualifier().storage) {
265 case glslang::EvqUniform:
266 case glslang::EvqBuffer:
267 switch (type.getQualifier().layoutPacking) {
268 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600269 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
270 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600271 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600272 }
273 case glslang::EvqVaryingIn:
274 case glslang::EvqVaryingOut:
275 if (type.getQualifier().layoutPacking != glslang::ElpNone)
276 spv::MissingFunctionality("in/out block layout");
277 return (spv::Decoration)spv::BadValue;
278 default:
279 spv::MissingFunctionality("block storage qualification");
280 return (spv::Decoration)spv::BadValue;
281 }
282 }
283 }
284}
285
286// Translate glslang type to SPIR-V interpolation decorations.
287spv::Decoration TranslateInterpolationDecoration(const glslang::TType& type)
288{
289 if (type.getQualifier().smooth)
290 return spv::DecorationSmooth;
291 if (type.getQualifier().nopersp)
292 return spv::DecorationNoperspective;
293 else if (type.getQualifier().patch)
294 return spv::DecorationPatch;
295 else if (type.getQualifier().flat)
296 return spv::DecorationFlat;
297 else if (type.getQualifier().centroid)
298 return spv::DecorationCentroid;
299 else if (type.getQualifier().sample)
300 return spv::DecorationSample;
301 else
302 return (spv::Decoration)spv::BadValue;
303}
304
305// If glslang type is invaraiant, return SPIR-V invariant decoration.
306spv::Decoration TranslateInvariantDecoration(const glslang::TType& type)
307{
308 if (type.getQualifier().invariant)
309 return spv::DecorationInvariant;
310 else
311 return (spv::Decoration)spv::BadValue;
312}
313
314// Translate glslang built-in variable to SPIR-V built in decoration.
315spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
316{
317 switch (builtIn) {
318 case glslang::EbvPosition: return spv::BuiltInPosition;
319 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600320 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
321 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
322 case glslang::EbvVertexId: return spv::BuiltInVertexId;
323 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
324 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
325 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
326 case glslang::EbvLayer: return spv::BuiltInLayer;
327 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
328 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
329 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
330 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
331 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
332 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
333 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
334 case glslang::EbvFace: return spv::BuiltInFrontFacing;
335 case glslang::EbvSampleId: return spv::BuiltInSampleId;
336 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
337 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
338 case glslang::EbvFragColor: return spv::BuiltInFragColor;
339 case glslang::EbvFragData: return spv::BuiltInFragColor;
340 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
341 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
342 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
343 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
344 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
345 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
346 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
347 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
348 default: return (spv::BuiltIn)spv::BadValue;
349 }
350}
351
Rex Xufc618912015-09-09 16:42:49 +0800352// Translate glslang image layout format to SPIR-V image format.
353spv::ImageFormat TranslateImageFormat(const glslang::TType& type)
354{
355 assert(type.getBasicType() == glslang::EbtSampler);
356
357 switch (type.getQualifier().layoutFormat) {
358 case glslang::ElfNone: return spv::ImageFormatUnknown;
359 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
360 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
361 case glslang::ElfR32f: return spv::ImageFormatR32f;
362 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
363 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
364 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
365 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
366 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
367 case glslang::ElfR16f: return spv::ImageFormatR16f;
368 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
369 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
370 case glslang::ElfRg16: return spv::ImageFormatRg16;
371 case glslang::ElfRg8: return spv::ImageFormatRg8;
372 case glslang::ElfR16: return spv::ImageFormatR16;
373 case glslang::ElfR8: return spv::ImageFormatR8;
374 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
375 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
376 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
377 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
378 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
379 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
380 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
381 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
382 case glslang::ElfR32i: return spv::ImageFormatR32i;
383 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
384 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
385 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
386 case glslang::ElfR16i: return spv::ImageFormatR16i;
387 case glslang::ElfR8i: return spv::ImageFormatR8i;
388 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
389 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
390 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
391 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
392 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
393 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
394 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
395 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
396 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
397 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
398 default: return (spv::ImageFormat)spv::BadValue;
399 }
400}
401
John Kessenich140f3df2015-06-26 16:58:36 -0600402//
403// Implement the TGlslangToSpvTraverser class.
404//
405
406TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
407 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
408 builder(GlslangMagic),
409 inMain(false), mainTerminated(false), linkageOnly(false),
410 glslangIntermediate(glslangIntermediate)
411{
412 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
413
414 builder.clearAccessChain();
415 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
416 stdBuiltins = builder.import("GLSL.std.450");
417 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
418 shaderEntry = builder.makeMain();
John Kessenich5e4b1242015-08-06 22:53:06 -0600419 builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600420
421 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600422 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
423 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600424 builder.addSourceExtension(it->c_str());
425
426 // Add the top-level modes for this shader.
427
428 if (glslangIntermediate->getXfbMode())
429 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
430
431 unsigned int mode;
432 switch (glslangIntermediate->getStage()) {
433 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600434 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600435 break;
436
437 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600438 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600439 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
440 break;
441
442 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600443 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600444 switch (glslangIntermediate->getInputPrimitive()) {
445 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
446 case glslang::ElgQuads: mode = spv::ExecutionModeInputQuads; break;
447 case glslang::ElgIsolines: mode = spv::ExecutionModeInputIsolines; break;
448 default: mode = spv::BadValue; break;
449 }
450 if (mode != spv::BadValue)
451 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
452
453 // TODO
454 //builder.addExecutionMode(spv::VertexSpacingMdName, glslangIntermediate->getVertexSpacing());
455 //builder.addExecutionMode(spv::VertexOrderMdName, glslangIntermediate->getVertexOrder());
456 //builder.addExecutionMode(spv::PointModeMdName, glslangIntermediate->getPointMode());
457 break;
458
459 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600460 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600461 switch (glslangIntermediate->getInputPrimitive()) {
462 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
463 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
464 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
465 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
466 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
467 default: mode = spv::BadValue; break;
468 }
469 if (mode != spv::BadValue)
470 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
471 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
472
473 switch (glslangIntermediate->getOutputPrimitive()) {
474 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
475 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
476 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
477 default: mode = spv::BadValue; break;
478 }
479 if (mode != spv::BadValue)
480 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
481 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
482 break;
483
484 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600485 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600486 if (glslangIntermediate->getPixelCenterInteger())
487 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
488 if (glslangIntermediate->getOriginUpperLeft())
489 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600490 else
491 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kessenich140f3df2015-06-26 16:58:36 -0600492 break;
493
494 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600495 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600496 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
497 glslangIntermediate->getLocalSize(1),
498 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600499 break;
500
501 default:
502 break;
503 }
504
505}
506
507TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
508{
509 if (! mainTerminated) {
510 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
511 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600512 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600513 }
514}
515
516//
517// Implement the traversal functions.
518//
519// Return true from interior nodes to have the external traversal
520// continue on to children. Return false if children were
521// already processed.
522//
523
524//
525// Symbols can turn into
526// - uniform/input reads
527// - output writes
528// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
529// - something simple that degenerates into the last bullet
530//
531void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
532{
533 // getSymbolId() will set up all the IO decorations on the first call.
534 // Formal function parameters were mapped during makeFunctions().
535 spv::Id id = getSymbolId(symbol);
536
537 if (! linkageOnly) {
538 // Prepare to generate code for the access
539
540 // L-value chains will be computed left to right. We're on the symbol now,
541 // which is the left-most part of the access chain, so now is "clear" time,
542 // followed by setting the base.
543 builder.clearAccessChain();
544
545 // For now, we consider all user variables as being in memory, so they are pointers,
546 // except for "const in" arguments to a function, which are an intermediate object.
547 // See comments in handleUserFunctionCall().
548 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
549 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
550 builder.setAccessChainRValue(id);
551 else
552 builder.setAccessChainLValue(id);
553 }
554}
555
556bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
557{
558 // First, handle special cases
559 switch (node->getOp()) {
560 case glslang::EOpAssign:
561 case glslang::EOpAddAssign:
562 case glslang::EOpSubAssign:
563 case glslang::EOpMulAssign:
564 case glslang::EOpVectorTimesMatrixAssign:
565 case glslang::EOpVectorTimesScalarAssign:
566 case glslang::EOpMatrixTimesScalarAssign:
567 case glslang::EOpMatrixTimesMatrixAssign:
568 case glslang::EOpDivAssign:
569 case glslang::EOpModAssign:
570 case glslang::EOpAndAssign:
571 case glslang::EOpInclusiveOrAssign:
572 case glslang::EOpExclusiveOrAssign:
573 case glslang::EOpLeftShiftAssign:
574 case glslang::EOpRightShiftAssign:
575 // A bin-op assign "a += b" means the same thing as "a = a + b"
576 // where a is evaluated before b. For a simple assignment, GLSL
577 // says to evaluate the left before the right. So, always, left
578 // node then right node.
579 {
580 // get the left l-value, save it away
581 builder.clearAccessChain();
582 node->getLeft()->traverse(this);
583 spv::Builder::AccessChain lValue = builder.getAccessChain();
584
585 // evaluate the right
586 builder.clearAccessChain();
587 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600588 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600589
590 if (node->getOp() != glslang::EOpAssign) {
591 // the left is also an r-value
592 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600593 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600594
595 // do the operation
596 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
597 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
598 node->getType().getBasicType());
599
600 // these all need their counterparts in createBinaryOperation()
601 if (rValue == 0)
602 spv::MissingFunctionality("createBinaryOperation");
603 }
604
605 // store the result
606 builder.setAccessChain(lValue);
607 builder.accessChainStore(rValue);
608
609 // assignments are expressions having an rValue after they are evaluated...
610 builder.clearAccessChain();
611 builder.setAccessChainRValue(rValue);
612 }
613 return false;
614 case glslang::EOpIndexDirect:
615 case glslang::EOpIndexDirectStruct:
616 {
617 // Get the left part of the access chain.
618 node->getLeft()->traverse(this);
619
620 // Add the next element in the chain
621
622 int index = 0;
623 if (node->getRight()->getAsConstantUnion() == 0)
624 spv::MissingFunctionality("direct index without a constant node");
625 else
626 index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
627
628 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
629 // This may be, e.g., an anonymous block-member selection, which generally need
630 // index remapping due to hidden members in anonymous blocks.
631 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
632 if (remapper.size() == 0)
633 spv::MissingFunctionality("block without member remapping");
634 else
635 index = remapper[index];
636 }
637
638 if (! node->getLeft()->getType().isArray() &&
639 node->getLeft()->getType().isVector() &&
640 node->getOp() == glslang::EOpIndexDirect) {
641 // This is essentially a hard-coded vector swizzle of size 1,
642 // so short circuit the access-chain stuff with a swizzle.
643 std::vector<unsigned> swizzle;
644 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600645 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600646 } else {
647 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600648 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600649 }
650 }
651 return false;
652 case glslang::EOpIndexIndirect:
653 {
654 // Structure or array or vector indirection.
655 // Will use native SPIR-V access-chain for struct and array indirection;
656 // matrices are arrays of vectors, so will also work for a matrix.
657 // Will use the access chain's 'component' for variable index into a vector.
658
659 // This adapter is building access chains left to right.
660 // Set up the access chain to the left.
661 node->getLeft()->traverse(this);
662
663 // save it so that computing the right side doesn't trash it
664 spv::Builder::AccessChain partial = builder.getAccessChain();
665
666 // compute the next index in the chain
667 builder.clearAccessChain();
668 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600669 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600670
671 // restore the saved access chain
672 builder.setAccessChain(partial);
673
674 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600675 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600676 else
John Kessenichfa668da2015-09-13 14:46:30 -0600677 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600678 }
679 return false;
680 case glslang::EOpVectorSwizzle:
681 {
682 node->getLeft()->traverse(this);
683 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
684 std::vector<unsigned> swizzle;
685 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
686 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600687 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600688 }
689 return false;
690 default:
691 break;
692 }
693
694 // Assume generic binary op...
695
696 // Get the operands
697 builder.clearAccessChain();
698 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600699 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600700
701 builder.clearAccessChain();
702 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600703 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600704
705 spv::Id result;
706 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
707
708 result = createBinaryOperation(node->getOp(), precision,
709 convertGlslangToSpvType(node->getType()), left, right,
710 node->getLeft()->getType().getBasicType());
711
712 if (! result) {
713 spv::MissingFunctionality("glslang binary operation");
714 } else {
715 builder.clearAccessChain();
716 builder.setAccessChainRValue(result);
717
718 return false;
719 }
720
721 return true;
722}
723
724bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
725{
John Kessenichfc51d282015-08-19 13:34:18 -0600726 spv::Id result = spv::NoResult;
727
728 // try texturing first
729 result = createImageTextureFunctionCall(node);
730 if (result != spv::NoResult) {
731 builder.clearAccessChain();
732 builder.setAccessChainRValue(result);
733
734 return false; // done with this node
735 }
736
737 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600738
739 if (node->getOp() == glslang::EOpArrayLength) {
740 // Quite special; won't want to evaluate the operand.
741
742 // Normal .length() would have been constant folded by the front-end.
743 // So, this has to be block.lastMember.length().
744 // SPV wants "block" as the operand, go get it.
745 assert(node->getOperand()->getType().isRuntimeSizedArray());
746 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
747 block->traverse(this);
748 spv::Id length = builder.createUnaryOp(spv::OpArrayLength, builder.makeIntType(32), builder.accessChainGetLValue());
749
750 builder.clearAccessChain();
751 builder.setAccessChainRValue(length);
752
753 return false;
754 }
755
John Kessenichfc51d282015-08-19 13:34:18 -0600756 // Start by evaluating the operand
757
John Kessenich140f3df2015-06-26 16:58:36 -0600758 builder.clearAccessChain();
759 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800760
Rex Xufc618912015-09-09 16:42:49 +0800761 spv::Id operand = spv::NoResult;
762
763 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
764 node->getOp() == glslang::EOpAtomicCounterDecrement ||
765 node->getOp() == glslang::EOpAtomicCounter)
766 operand = builder.accessChainGetLValue(); // Special case l-value operands
767 else
Rex Xu30f92582015-09-14 10:38:56 +0800768 operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600769
770 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
771
772 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600773 if (! result)
774 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600775
776 // if not, then possibly an operation
777 if (! result)
Rex Xu04db3f52015-09-16 11:44:02 +0800778 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600779
780 if (result) {
781 builder.clearAccessChain();
782 builder.setAccessChainRValue(result);
783
784 return false; // done with this node
785 }
786
787 // it must be a special case, check...
788 switch (node->getOp()) {
789 case glslang::EOpPostIncrement:
790 case glslang::EOpPostDecrement:
791 case glslang::EOpPreIncrement:
792 case glslang::EOpPreDecrement:
793 {
794 // we need the integer value "1" or the floating point "1.0" to add/subtract
795 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
796 builder.makeFloatConstant(1.0F) :
797 builder.makeIntConstant(1);
798 glslang::TOperator op;
799 if (node->getOp() == glslang::EOpPreIncrement ||
800 node->getOp() == glslang::EOpPostIncrement)
801 op = glslang::EOpAdd;
802 else
803 op = glslang::EOpSub;
804
805 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
806 convertGlslangToSpvType(node->getType()), operand, one,
807 node->getType().getBasicType());
808 if (result == 0)
809 spv::MissingFunctionality("createBinaryOperation for unary");
810
811 // The result of operation is always stored, but conditionally the
812 // consumed result. The consumed result is always an r-value.
813 builder.accessChainStore(result);
814 builder.clearAccessChain();
815 if (node->getOp() == glslang::EOpPreIncrement ||
816 node->getOp() == glslang::EOpPreDecrement)
817 builder.setAccessChainRValue(result);
818 else
819 builder.setAccessChainRValue(operand);
820 }
821
822 return false;
823
824 case glslang::EOpEmitStreamVertex:
825 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
826 return false;
827 case glslang::EOpEndStreamPrimitive:
828 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
829 return false;
830
831 default:
832 spv::MissingFunctionality("glslang unary");
833 break;
834 }
835
836 return true;
837}
838
839bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
840{
John Kessenichfc51d282015-08-19 13:34:18 -0600841 spv::Id result = spv::NoResult;
842
843 // try texturing
844 result = createImageTextureFunctionCall(node);
845 if (result != spv::NoResult) {
846 builder.clearAccessChain();
847 builder.setAccessChainRValue(result);
848
849 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600850 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800851 // "imageStore" is a special case, which has no result
852 return false;
853 }
John Kessenichfc51d282015-08-19 13:34:18 -0600854
John Kessenich140f3df2015-06-26 16:58:36 -0600855 glslang::TOperator binOp = glslang::EOpNull;
856 bool reduceComparison = true;
857 bool isMatrix = false;
858 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600859 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600860
861 assert(node->getOp());
862
863 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
864
865 switch (node->getOp()) {
866 case glslang::EOpSequence:
867 {
868 if (preVisit)
869 ++sequenceDepth;
870 else
871 --sequenceDepth;
872
873 if (sequenceDepth == 1) {
874 // If this is the parent node of all the functions, we want to see them
875 // early, so all call points have actual SPIR-V functions to reference.
876 // In all cases, still let the traverser visit the children for us.
877 makeFunctions(node->getAsAggregate()->getSequence());
878
879 // Also, we want all globals initializers to go into the entry of main(), before
880 // anything else gets there, so visit out of order, doing them all now.
881 makeGlobalInitializers(node->getAsAggregate()->getSequence());
882
883 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
884 // so do them manually.
885 visitFunctions(node->getAsAggregate()->getSequence());
886
887 return false;
888 }
889
890 return true;
891 }
892 case glslang::EOpLinkerObjects:
893 {
894 if (visit == glslang::EvPreVisit)
895 linkageOnly = true;
896 else
897 linkageOnly = false;
898
899 return true;
900 }
901 case glslang::EOpComma:
902 {
903 // processing from left to right naturally leaves the right-most
904 // lying around in the access chain
905 glslang::TIntermSequence& glslangOperands = node->getSequence();
906 for (int i = 0; i < (int)glslangOperands.size(); ++i)
907 glslangOperands[i]->traverse(this);
908
909 return false;
910 }
911 case glslang::EOpFunction:
912 if (visit == glslang::EvPreVisit) {
913 if (isShaderEntrypoint(node)) {
914 inMain = true;
915 builder.setBuildPoint(shaderEntry->getLastBlock());
916 } else {
917 handleFunctionEntry(node);
918 }
919 } else {
920 if (inMain)
921 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -0600922 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600923 inMain = false;
924 }
925
926 return true;
927 case glslang::EOpParameters:
928 // Parameters will have been consumed by EOpFunction processing, but not
929 // the body, so we still visited the function node's children, making this
930 // child redundant.
931 return false;
932 case glslang::EOpFunctionCall:
933 {
934 if (node->isUserDefined())
935 result = handleUserFunctionCall(node);
John Kessenich140f3df2015-06-26 16:58:36 -0600936
937 if (! result) {
938 spv::MissingFunctionality("glslang function call");
939 glslang::TConstUnionArray emptyConsts;
940 int nextConst = 0;
941 result = createSpvConstant(node->getType(), emptyConsts, nextConst);
942 }
943 builder.clearAccessChain();
944 builder.setAccessChainRValue(result);
945
946 return false;
947 }
948 case glslang::EOpConstructMat2x2:
949 case glslang::EOpConstructMat2x3:
950 case glslang::EOpConstructMat2x4:
951 case glslang::EOpConstructMat3x2:
952 case glslang::EOpConstructMat3x3:
953 case glslang::EOpConstructMat3x4:
954 case glslang::EOpConstructMat4x2:
955 case glslang::EOpConstructMat4x3:
956 case glslang::EOpConstructMat4x4:
957 case glslang::EOpConstructDMat2x2:
958 case glslang::EOpConstructDMat2x3:
959 case glslang::EOpConstructDMat2x4:
960 case glslang::EOpConstructDMat3x2:
961 case glslang::EOpConstructDMat3x3:
962 case glslang::EOpConstructDMat3x4:
963 case glslang::EOpConstructDMat4x2:
964 case glslang::EOpConstructDMat4x3:
965 case glslang::EOpConstructDMat4x4:
966 isMatrix = true;
967 // fall through
968 case glslang::EOpConstructFloat:
969 case glslang::EOpConstructVec2:
970 case glslang::EOpConstructVec3:
971 case glslang::EOpConstructVec4:
972 case glslang::EOpConstructDouble:
973 case glslang::EOpConstructDVec2:
974 case glslang::EOpConstructDVec3:
975 case glslang::EOpConstructDVec4:
976 case glslang::EOpConstructBool:
977 case glslang::EOpConstructBVec2:
978 case glslang::EOpConstructBVec3:
979 case glslang::EOpConstructBVec4:
980 case glslang::EOpConstructInt:
981 case glslang::EOpConstructIVec2:
982 case glslang::EOpConstructIVec3:
983 case glslang::EOpConstructIVec4:
984 case glslang::EOpConstructUint:
985 case glslang::EOpConstructUVec2:
986 case glslang::EOpConstructUVec3:
987 case glslang::EOpConstructUVec4:
988 case glslang::EOpConstructStruct:
989 {
990 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +0800991 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -0600992 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
993 spv::Id constructed;
994 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
995 std::vector<spv::Id> constituents;
996 for (int c = 0; c < (int)arguments.size(); ++c)
997 constituents.push_back(arguments[c]);
998 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
999 } else {
1000 if (isMatrix)
1001 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1002 else
1003 constructed = builder.createConstructor(precision, arguments, resultTypeId);
1004 }
1005
1006 builder.clearAccessChain();
1007 builder.setAccessChainRValue(constructed);
1008
1009 return false;
1010 }
1011
1012 // These six are component-wise compares with component-wise results.
1013 // Forward on to createBinaryOperation(), requesting a vector result.
1014 case glslang::EOpLessThan:
1015 case glslang::EOpGreaterThan:
1016 case glslang::EOpLessThanEqual:
1017 case glslang::EOpGreaterThanEqual:
1018 case glslang::EOpVectorEqual:
1019 case glslang::EOpVectorNotEqual:
1020 {
1021 // Map the operation to a binary
1022 binOp = node->getOp();
1023 reduceComparison = false;
1024 switch (node->getOp()) {
1025 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1026 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1027 default: binOp = node->getOp(); break;
1028 }
1029
1030 break;
1031 }
1032 case glslang::EOpMul:
1033 // compontent-wise matrix multiply
1034 binOp = glslang::EOpMul;
1035 break;
1036 case glslang::EOpOuterProduct:
1037 // two vectors multiplied to make a matrix
1038 binOp = glslang::EOpOuterProduct;
1039 break;
1040 case glslang::EOpDot:
1041 {
1042 // for scalar dot product, use multiply
1043 glslang::TIntermSequence& glslangOperands = node->getSequence();
1044 if (! glslangOperands[0]->getAsTyped()->isVector())
1045 binOp = glslang::EOpMul;
1046 break;
1047 }
1048 case glslang::EOpMod:
1049 // when an aggregate, this is the floating-point mod built-in function,
1050 // which can be emitted by the one in createBinaryOperation()
1051 binOp = glslang::EOpMod;
1052 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001053 case glslang::EOpEmitVertex:
1054 case glslang::EOpEndPrimitive:
1055 case glslang::EOpBarrier:
1056 case glslang::EOpMemoryBarrier:
1057 case glslang::EOpMemoryBarrierAtomicCounter:
1058 case glslang::EOpMemoryBarrierBuffer:
1059 case glslang::EOpMemoryBarrierImage:
1060 case glslang::EOpMemoryBarrierShared:
1061 case glslang::EOpGroupMemoryBarrier:
1062 noReturnValue = true;
1063 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1064 break;
1065
John Kessenich426394d2015-07-23 10:22:48 -06001066 case glslang::EOpAtomicAdd:
1067 case glslang::EOpAtomicMin:
1068 case glslang::EOpAtomicMax:
1069 case glslang::EOpAtomicAnd:
1070 case glslang::EOpAtomicOr:
1071 case glslang::EOpAtomicXor:
1072 case glslang::EOpAtomicExchange:
1073 case glslang::EOpAtomicCompSwap:
1074 atomic = true;
1075 break;
1076
John Kessenichfc51d282015-08-19 13:34:18 -06001077 case glslang::EOpAddCarry:
1078 case glslang::EOpSubBorrow:
1079 case glslang::EOpUMulExtended:
1080 case glslang::EOpIMulExtended:
1081 case glslang::EOpBitfieldExtract:
1082 case glslang::EOpBitfieldInsert:
1083 spv::MissingFunctionality("integer aggregate");
1084 break;
1085
1086 case glslang::EOpFma:
John Kessenich78258d32015-08-19 17:30:12 -06001087 case glslang::EOpFrexp:
1088 case glslang::EOpLdexp:
John Kessenichfc51d282015-08-19 13:34:18 -06001089 spv::MissingFunctionality("fma/frexp/ldexp aggregate");
1090 break;
1091
John Kessenich140f3df2015-06-26 16:58:36 -06001092 default:
1093 break;
1094 }
1095
1096 //
1097 // See if it maps to a regular operation.
1098 //
John Kessenich140f3df2015-06-26 16:58:36 -06001099 if (binOp != glslang::EOpNull) {
1100 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1101 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1102 assert(left && right);
1103
1104 builder.clearAccessChain();
1105 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001106 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001107
1108 builder.clearAccessChain();
1109 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001110 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001111
1112 result = createBinaryOperation(binOp, precision,
1113 convertGlslangToSpvType(node->getType()), leftId, rightId,
1114 left->getType().getBasicType(), reduceComparison);
1115
1116 // code above should only make binOp that exists in createBinaryOperation
1117 if (result == 0)
1118 spv::MissingFunctionality("createBinaryOperation for aggregate");
1119
1120 builder.clearAccessChain();
1121 builder.setAccessChainRValue(result);
1122
1123 return false;
1124 }
1125
John Kessenich426394d2015-07-23 10:22:48 -06001126 //
1127 // Create the list of operands.
1128 //
John Kessenich140f3df2015-06-26 16:58:36 -06001129 glslang::TIntermSequence& glslangOperands = node->getSequence();
1130 std::vector<spv::Id> operands;
1131 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1132 builder.clearAccessChain();
1133 glslangOperands[arg]->traverse(this);
1134
1135 // special case l-value operands; there are just a few
1136 bool lvalue = false;
1137 switch (node->getOp()) {
1138 //case glslang::EOpFrexp:
1139 case glslang::EOpModf:
1140 if (arg == 1)
1141 lvalue = true;
1142 break;
Rex Xud4782c12015-09-06 16:30:11 +08001143 case glslang::EOpAtomicAdd:
1144 case glslang::EOpAtomicMin:
1145 case glslang::EOpAtomicMax:
1146 case glslang::EOpAtomicAnd:
1147 case glslang::EOpAtomicOr:
1148 case glslang::EOpAtomicXor:
1149 case glslang::EOpAtomicExchange:
1150 case glslang::EOpAtomicCompSwap:
1151 if (arg == 0)
1152 lvalue = true;
1153 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001154 //case glslang::EOpUAddCarry:
1155 //case glslang::EOpUSubBorrow:
1156 //case glslang::EOpUMulExtended:
1157 default:
1158 break;
1159 }
1160 if (lvalue)
1161 operands.push_back(builder.accessChainGetLValue());
1162 else
John Kessenichfa668da2015-09-13 14:46:30 -06001163 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001164 }
John Kessenich426394d2015-07-23 10:22:48 -06001165
1166 if (atomic) {
1167 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001168 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001169 } else {
1170 // Pass through to generic operations.
1171 switch (glslangOperands.size()) {
1172 case 0:
1173 result = createNoArgOperation(node->getOp());
1174 break;
1175 case 1:
Rex Xu04db3f52015-09-16 11:44:02 +08001176 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), node->getType().getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001177 break;
1178 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001179 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001180 break;
1181 }
John Kessenich140f3df2015-06-26 16:58:36 -06001182 }
1183
1184 if (noReturnValue)
1185 return false;
1186
1187 if (! result) {
1188 spv::MissingFunctionality("glslang aggregate");
1189 return true;
1190 } else {
1191 builder.clearAccessChain();
1192 builder.setAccessChainRValue(result);
1193 return false;
1194 }
1195}
1196
1197bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1198{
1199 // This path handles both if-then-else and ?:
1200 // The if-then-else has a node type of void, while
1201 // ?: has a non-void node type
1202 spv::Id result = 0;
1203 if (node->getBasicType() != glslang::EbtVoid) {
1204 // don't handle this as just on-the-fly temporaries, because there will be two names
1205 // and better to leave SSA to later passes
1206 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1207 }
1208
1209 // emit the condition before doing anything with selection
1210 node->getCondition()->traverse(this);
1211
1212 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001213 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001214
1215 if (node->getTrueBlock()) {
1216 // emit the "then" statement
1217 node->getTrueBlock()->traverse(this);
1218 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001219 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001220 }
1221
1222 if (node->getFalseBlock()) {
1223 ifBuilder.makeBeginElse();
1224 // emit the "else" statement
1225 node->getFalseBlock()->traverse(this);
1226 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001227 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001228 }
1229
1230 ifBuilder.makeEndIf();
1231
1232 if (result) {
1233 // GLSL only has r-values as the result of a :?, but
1234 // if we have an l-value, that can be more efficient if it will
1235 // become the base of a complex r-value expression, because the
1236 // next layer copies r-values into memory to use the access-chain mechanism
1237 builder.clearAccessChain();
1238 builder.setAccessChainLValue(result);
1239 }
1240
1241 return false;
1242}
1243
1244bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1245{
1246 // emit and get the condition before doing anything with switch
1247 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001248 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001249
1250 // browse the children to sort out code segments
1251 int defaultSegment = -1;
1252 std::vector<TIntermNode*> codeSegments;
1253 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1254 std::vector<int> caseValues;
1255 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1256 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1257 TIntermNode* child = *c;
1258 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001259 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001260 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001261 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001262 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1263 } else
1264 codeSegments.push_back(child);
1265 }
1266
1267 // handle the case where the last code segment is missing, due to no code
1268 // statements between the last case and the end of the switch statement
1269 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1270 (int)codeSegments.size() == defaultSegment)
1271 codeSegments.push_back(nullptr);
1272
1273 // make the switch statement
1274 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001275 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001276
1277 // emit all the code in the segments
1278 breakForLoop.push(false);
1279 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1280 builder.nextSwitchSegment(segmentBlocks, s);
1281 if (codeSegments[s])
1282 codeSegments[s]->traverse(this);
1283 else
1284 builder.addSwitchBreak();
1285 }
1286 breakForLoop.pop();
1287
1288 builder.endSwitch(segmentBlocks);
1289
1290 return false;
1291}
1292
1293void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1294{
1295 int nextConst = 0;
1296 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1297
1298 builder.clearAccessChain();
1299 builder.setAccessChainRValue(constant);
1300}
1301
1302bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1303{
1304 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1305 loopTerminal.push(node->getTerminal());
1306
David Netoc22f37c2015-07-15 16:21:26 -04001307 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001308
1309 if (node->getTest()) {
1310 node->getTest()->traverse(this);
1311 // the AST only contained the test computation, not the branch, we have to add it
John Kessenichfa668da2015-09-13 14:46:30 -06001312 spv::Id condition = builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001313 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001314 } else {
1315 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001316 }
1317
David Netoc22f37c2015-07-15 16:21:26 -04001318 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001319 breakForLoop.push(true);
1320 node->getBody()->traverse(this);
1321 breakForLoop.pop();
1322 }
1323
1324 if (loopTerminal.top())
1325 loopTerminal.top()->traverse(this);
1326
1327 builder.closeLoop();
1328
1329 loopTerminal.pop();
1330
1331 return false;
1332}
1333
1334bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1335{
1336 if (node->getExpression())
1337 node->getExpression()->traverse(this);
1338
1339 switch (node->getFlowOp()) {
1340 case glslang::EOpKill:
1341 builder.makeDiscard();
1342 break;
1343 case glslang::EOpBreak:
1344 if (breakForLoop.top())
1345 builder.createLoopExit();
1346 else
1347 builder.addSwitchBreak();
1348 break;
1349 case glslang::EOpContinue:
1350 if (loopTerminal.top())
1351 loopTerminal.top()->traverse(this);
1352 builder.createLoopContinue();
1353 break;
1354 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001355 if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001356 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001357 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001358 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001359
1360 builder.clearAccessChain();
1361 break;
1362
1363 default:
1364 spv::MissingFunctionality("branch type");
1365 break;
1366 }
1367
1368 return false;
1369}
1370
1371spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1372{
1373 // First, steer off constants, which are not SPIR-V variables, but
1374 // can still have a mapping to a SPIR-V Id.
1375 if (node->getQualifier().storage == glslang::EvqConst) {
1376 int nextConst = 0;
1377 return createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1378 }
1379
1380 // Now, handle actual variables
1381 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1382 spv::Id spvType = convertGlslangToSpvType(node->getType());
1383
1384 const char* name = node->getName().c_str();
1385 if (glslang::IsAnonymous(name))
1386 name = "";
1387
1388 return builder.createVariable(storageClass, spvType, name);
1389}
1390
1391// Return type Id of the sampled type.
1392spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1393{
1394 switch (sampler.type) {
1395 case glslang::EbtFloat: return builder.makeFloatType(32);
1396 case glslang::EbtInt: return builder.makeIntType(32);
1397 case glslang::EbtUint: return builder.makeUintType(32);
1398 default:
1399 spv::MissingFunctionality("sampled type");
1400 return builder.makeFloatType(32);
1401 }
1402}
1403
John Kessenich31ed4832015-09-09 17:51:38 -06001404// Convert from a glslang type to an SPV type, by calling into
1405// recursive version of this function.
John Kessenich140f3df2015-06-26 16:58:36 -06001406spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1407{
John Kessenich31ed4832015-09-09 17:51:38 -06001408 return convertGlslangToSpvType(type, requiresExplicitLayout(type));
1409}
1410
1411// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1412// explicitLayout can be kept the same throughout the heirarchical recursive walk.
1413spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout)
1414{
John Kessenich140f3df2015-06-26 16:58:36 -06001415 spv::Id spvType = 0;
1416
1417 switch (type.getBasicType()) {
1418 case glslang::EbtVoid:
1419 spvType = builder.makeVoidType();
1420 if (type.isArray())
1421 spv::MissingFunctionality("array of void");
1422 break;
1423 case glslang::EbtFloat:
1424 spvType = builder.makeFloatType(32);
1425 break;
1426 case glslang::EbtDouble:
1427 spvType = builder.makeFloatType(64);
1428 break;
1429 case glslang::EbtBool:
1430 spvType = builder.makeBoolType();
1431 break;
1432 case glslang::EbtInt:
1433 spvType = builder.makeIntType(32);
1434 break;
1435 case glslang::EbtUint:
1436 spvType = builder.makeUintType(32);
1437 break;
John Kessenich426394d2015-07-23 10:22:48 -06001438 case glslang::EbtAtomicUint:
1439 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1440 spvType = builder.makeUintType(32);
1441 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001442 case glslang::EbtSampler:
1443 {
1444 const glslang::TSampler& sampler = type.getSampler();
John Kessenich5e4b1242015-08-06 22:53:06 -06001445 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
Rex Xufc618912015-09-09 16:42:49 +08001446 sampler.image ? 2 : 1, TranslateImageFormat(type));
John Kessenich5e4b1242015-08-06 22:53:06 -06001447 // OpenGL "textures" need to be combined with a sampler
1448 if (! sampler.image)
1449 spvType = builder.makeSampledImageType(spvType);
John Kessenich140f3df2015-06-26 16:58:36 -06001450 }
1451 break;
1452 case glslang::EbtStruct:
1453 case glslang::EbtBlock:
1454 {
1455 // If we've seen this struct type, return it
1456 const glslang::TTypeList* glslangStruct = type.getStruct();
1457 std::vector<spv::Id> structFields;
1458 spvType = structMap[glslangStruct];
1459 if (spvType)
1460 break;
1461
1462 // else, we haven't seen it...
1463
1464 // Create a vector of struct types for SPIR-V to consume
1465 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1466 if (type.getBasicType() == glslang::EbtBlock)
1467 memberRemapper[glslangStruct].resize(glslangStruct->size());
1468 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1469 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1470 if (glslangType.hiddenMember()) {
1471 ++memberDelta;
1472 if (type.getBasicType() == glslang::EbtBlock)
1473 memberRemapper[glslangStruct][i] = -1;
1474 } else {
1475 if (type.getBasicType() == glslang::EbtBlock)
1476 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kessenich31ed4832015-09-09 17:51:38 -06001477 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001478 }
1479 }
1480
1481 // Make the SPIR-V type
1482 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
1483 structMap[glslangStruct] = spvType;
1484
1485 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001486 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001487 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1488 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1489 int member = i;
1490 if (type.getBasicType() == glslang::EbtBlock)
1491 member = memberRemapper[glslangStruct][i];
1492 // using -1 above to indicate a hidden member
1493 if (member >= 0) {
1494 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
1495 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType));
1496 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1497 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1498 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1499 if (glslangType.getQualifier().hasLocation())
1500 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1501 if (glslangType.getQualifier().hasComponent())
1502 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1503 if (glslangType.getQualifier().hasXfbOffset())
1504 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenich31ed4832015-09-09 17:51:38 -06001505 else if (explicitLayout) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001506 // figure out what to do with offset, which is accumulating
1507 int nextOffset;
1508 updateMemberOffset(type, glslangType, offset, nextOffset);
1509 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001510 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001511 offset = nextOffset;
1512 }
John Kessenich140f3df2015-06-26 16:58:36 -06001513
John Kessenich31ed4832015-09-09 17:51:38 -06001514 if (glslangType.isMatrix() && explicitLayout) {
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001515 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType));
1516 }
1517
John Kessenich140f3df2015-06-26 16:58:36 -06001518 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001519 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1520 if (builtIn != spv::BadValue)
1521 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001522 }
1523 }
1524
1525 // Decorate the structure
1526 addDecoration(spvType, TranslateLayoutDecoration(type));
1527 addDecoration(spvType, TranslateBlockDecoration(type));
1528 if (type.getQualifier().hasStream())
1529 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1530 if (glslangIntermediate->getXfbMode()) {
1531 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001532 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001533 if (type.getQualifier().hasXfbBuffer())
1534 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1535 }
1536 }
1537 break;
1538 default:
1539 spv::MissingFunctionality("basic type");
1540 break;
1541 }
1542
1543 if (type.isMatrix())
1544 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1545 else {
1546 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1547 if (type.getVectorSize() > 1)
1548 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1549 }
1550
1551 if (type.isArray()) {
John Kessenichc9a80832015-09-12 12:17:44 -06001552 // Do all but the outer dimension
1553 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1554 assert(type.getArraySizes()->getDimSize(dim) > 0);
1555 spvType = builder.makeArrayType(spvType, type.getArraySizes()->getDimSize(dim));
1556 }
John Kessenich31ed4832015-09-09 17:51:38 -06001557
John Kessenichc9a80832015-09-12 12:17:44 -06001558 // Do the outer dimension, which might not be known for a runtime-sized array
1559 if (type.isRuntimeSizedArray()) {
1560 spvType = builder.makeRuntimeArray(spvType);
1561 } else {
1562 assert(type.getOuterArraySize() > 0);
1563 spvType = builder.makeArrayType(spvType, type.getOuterArraySize());
1564 }
1565
1566 // TODO: layout still needs to be done hierarchically for arrays of arrays, which
1567 // may still require additional "link time" support from the front-end
1568 // for arrays of arrays
John Kessenich31ed4832015-09-09 17:51:38 -06001569 if (explicitLayout)
1570 builder.addDecoration(spvType, spv::DecorationArrayStride, getArrayStride(type));
John Kessenich140f3df2015-06-26 16:58:36 -06001571 }
1572
1573 return spvType;
1574}
1575
John Kessenich31ed4832015-09-09 17:51:38 -06001576bool TGlslangToSpvTraverser::requiresExplicitLayout(const glslang::TType& type) const
1577{
1578 return type.getBasicType() == glslang::EbtBlock &&
1579 type.getQualifier().layoutPacking != glslang::ElpShared &&
1580 type.getQualifier().layoutPacking != glslang::ElpPacked &&
1581 (type.getQualifier().storage == glslang::EvqUniform ||
1582 type.getQualifier().storage == glslang::EvqBuffer);
1583}
1584
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001585// Given an array type, returns the integer stride required for that array
1586int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType)
1587{
1588 glslang::TType derefType(arrayType, 0);
1589 int size;
1590 glslangIntermediate->getBaseAlignment(derefType, size, true);
1591 return size;
1592}
1593
1594// Given a matrix type, returns the integer stride required for that matrix
1595// when used as a member of an interface block
1596int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType)
1597{
1598 int size;
1599 return glslangIntermediate->getBaseAlignment(matrixType, size, true);
1600}
1601
John Kessenich5e4b1242015-08-06 22:53:06 -06001602// Given a member type of a struct, realign the current offset for it, and compute
1603// the next (not yet aligned) offset for the next member, which will get aligned
1604// on the next call.
1605// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1606// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1607// -1 means a non-forced member offset (no decoration needed).
1608void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset)
1609{
1610 // this will get a positive value when deemed necessary
1611 nextOffset = -1;
1612
1613 bool forceOffset = structType.getQualifier().layoutPacking == glslang::ElpStd140 ||
1614 structType.getQualifier().layoutPacking == glslang::ElpStd430;
1615
1616 // override anything in currentOffset with user-set offset
1617 if (memberType.getQualifier().hasOffset())
1618 currentOffset = memberType.getQualifier().layoutOffset;
1619
1620 // It could be that current linker usage in glslang updated all the layoutOffset,
1621 // in which case the following code does not matter. But, that's not quite right
1622 // once cross-compilation unit GLSL validation is done, as the original user
1623 // settings are needed in layoutOffset, and then the following will come into play.
1624
1625 if (! forceOffset) {
1626 if (! memberType.getQualifier().hasOffset())
1627 currentOffset = -1;
1628
1629 return;
1630 }
1631
1632 // Getting this far means we are forcing offsets
1633 if (currentOffset < 0)
1634 currentOffset = 0;
1635
1636 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1637 // but possibly not yet correctly aligned.
1638
1639 int memberSize;
1640 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, memberType.getQualifier().layoutPacking == glslang::ElpStd140);
1641 glslang::RoundToPow2(currentOffset, memberAlignment);
1642 nextOffset = currentOffset + memberSize;
1643}
1644
John Kessenich140f3df2015-06-26 16:58:36 -06001645bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1646{
1647 return node->getName() == "main(";
1648}
1649
1650// Make all the functions, skeletally, without actually visiting their bodies.
1651void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1652{
1653 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1654 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1655 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1656 continue;
1657
1658 // We're on a user function. Set up the basic interface for the function now,
1659 // so that it's available to call.
1660 // Translating the body will happen later.
1661 //
1662 // Typically (except for a "const in" parameter), an address will be passed to the
1663 // function. What it is an address of varies:
1664 //
1665 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1666 // so that write needs to be to a copy, hence the address of a copy works.
1667 //
1668 // - "const in" parameters can just be the r-value, as no writes need occur.
1669 //
1670 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1671 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1672
1673 std::vector<spv::Id> paramTypes;
1674 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1675
1676 for (int p = 0; p < (int)parameters.size(); ++p) {
1677 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1678 spv::Id typeId = convertGlslangToSpvType(paramType);
1679 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1680 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1681 else
1682 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1683 paramTypes.push_back(typeId);
1684 }
1685
1686 spv::Block* functionBlock;
1687 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1688 paramTypes, &functionBlock);
1689
1690 // Track function to emit/call later
1691 functionMap[glslFunction->getName().c_str()] = function;
1692
1693 // Set the parameter id's
1694 for (int p = 0; p < (int)parameters.size(); ++p) {
1695 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1696 // give a name too
1697 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1698 }
1699 }
1700}
1701
1702// Process all the initializers, while skipping the functions and link objects
1703void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1704{
1705 builder.setBuildPoint(shaderEntry->getLastBlock());
1706 for (int i = 0; i < (int)initializers.size(); ++i) {
1707 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1708 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1709
1710 // We're on a top-level node that's not a function. Treat as an initializer, whose
1711 // code goes into the beginning of main.
1712 initializer->traverse(this);
1713 }
1714 }
1715}
1716
1717// Process all the functions, while skipping initializers.
1718void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1719{
1720 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1721 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1722 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1723 node->traverse(this);
1724 }
1725}
1726
1727void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1728{
1729 // SPIR-V functions should already be in the functionMap from the prepass
1730 // that called makeFunctions().
1731 spv::Function* function = functionMap[node->getName().c_str()];
1732 spv::Block* functionBlock = function->getEntryBlock();
1733 builder.setBuildPoint(functionBlock);
1734}
1735
Rex Xu04db3f52015-09-16 11:44:02 +08001736void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001737{
Rex Xufc618912015-09-09 16:42:49 +08001738 const glslang::TIntermSequence& glslangArguments = node.getSequence();
John Kessenich140f3df2015-06-26 16:58:36 -06001739 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1740 builder.clearAccessChain();
1741 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001742
1743 // Special case l-value operands
1744 bool lvalue = false;
1745 switch (node.getOp()) {
1746 case glslang::EOpImageAtomicAdd:
1747 case glslang::EOpImageAtomicMin:
1748 case glslang::EOpImageAtomicMax:
1749 case glslang::EOpImageAtomicAnd:
1750 case glslang::EOpImageAtomicOr:
1751 case glslang::EOpImageAtomicXor:
1752 case glslang::EOpImageAtomicExchange:
1753 case glslang::EOpImageAtomicCompSwap:
1754 if (i == 0)
1755 lvalue = true;
1756 break;
1757 default:
1758 break;
1759 }
1760
Rex Xu6b86d492015-09-16 17:48:22 +08001761 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08001762 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08001763 else
Rex Xu30f92582015-09-14 10:38:56 +08001764 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001765 }
1766}
1767
John Kessenichfc51d282015-08-19 13:34:18 -06001768void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001769{
John Kessenichfc51d282015-08-19 13:34:18 -06001770 builder.clearAccessChain();
1771 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001772 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06001773}
John Kessenich140f3df2015-06-26 16:58:36 -06001774
John Kessenichfc51d282015-08-19 13:34:18 -06001775spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1776{
Rex Xufc618912015-09-09 16:42:49 +08001777 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06001778 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001779 }
1780
John Kessenichfc51d282015-08-19 13:34:18 -06001781 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06001782 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1783 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1784 std::vector<spv::Id> arguments;
1785 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08001786 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06001787 else
1788 translateArguments(*node->getAsUnaryNode(), arguments);
1789 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1790
1791 spv::Builder::TextureParameters params = { };
1792 params.sampler = arguments[0];
1793
Rex Xu04db3f52015-09-16 11:44:02 +08001794 glslang::TCrackedTextureOp cracked;
1795 node->crackTexture(sampler, cracked);
1796
John Kessenichfc51d282015-08-19 13:34:18 -06001797 // Check for queries
1798 if (cracked.query) {
1799 switch (node->getOp()) {
1800 case glslang::EOpImageQuerySize:
1801 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001802 if (arguments.size() > 1) {
1803 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001804 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001805 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001806 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001807 case glslang::EOpImageQuerySamples:
1808 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001809 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001810 case glslang::EOpTextureQueryLod:
1811 params.coords = arguments[1];
1812 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1813 case glslang::EOpTextureQueryLevels:
1814 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1815 default:
1816 assert(0);
1817 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001818 }
John Kessenich140f3df2015-06-26 16:58:36 -06001819 }
1820
Rex Xufc618912015-09-09 16:42:49 +08001821 // Check for image functions other than queries
1822 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06001823 std::vector<spv::Id> operands;
1824 auto opIt = arguments.begin();
1825 operands.push_back(*(opIt++));
1826 operands.push_back(*(opIt++));
1827 if (node->getOp() == glslang::EOpImageStore)
Rex Xu6b86d492015-09-16 17:48:22 +08001828 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06001829 // TODO: add 'sample' operand
1830 if (node->getOp() == glslang::EOpImageLoad) {
1831 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
1832 } else if (node->getOp() == glslang::EOpImageStore) {
1833 builder.createNoResultOp(spv::OpImageWrite, operands);
1834 return spv::NoResult;
Rex Xu6b86d492015-09-16 17:48:22 +08001835 } else {
1836 // Process image atomic operations
1837
1838 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
1839 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich56bab042015-09-16 10:54:31 -06001840 operands.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06001841
Rex Xufc618912015-09-09 16:42:49 +08001842 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06001843 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08001844
1845 std::vector<spv::Id> operands;
1846 operands.push_back(pointer);
1847 for (; opIt != arguments.end(); ++opIt)
1848 operands.push_back(*opIt);
1849
Rex Xu04db3f52015-09-16 11:44:02 +08001850 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08001851 }
1852 }
1853
1854 // Check for texture functions other than queries
John Kessenichfc51d282015-08-19 13:34:18 -06001855 if (cracked.gather)
1856 spv::MissingFunctionality("texture gather");
1857
1858 // check for bias argument
1859 bool bias = false;
1860 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch) {
1861 int nonBiasArgCount = 2;
1862 if (cracked.offset)
1863 ++nonBiasArgCount;
1864 if (cracked.grad)
1865 nonBiasArgCount += 2;
1866
1867 if ((int)arguments.size() > nonBiasArgCount)
1868 bias = true;
1869 }
1870
1871 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1872
1873 // set the rest of the arguments
1874 params.coords = arguments[1];
1875 int extraArgs = 0;
1876 if (cubeCompare)
1877 params.Dref = arguments[2];
1878 else if (sampler.shadow) {
1879 std::vector<spv::Id> indexes;
1880 int comp;
1881 if (cracked.proj)
1882 comp = 3;
1883 else
1884 comp = builder.getNumComponents(params.coords) - 1;
1885 indexes.push_back(comp);
1886 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1887 }
1888 if (cracked.lod) {
1889 params.lod = arguments[2];
1890 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08001891 } else if (sampler.ms) {
1892 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08001893 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06001894 }
1895 if (cracked.grad) {
1896 params.gradX = arguments[2 + extraArgs];
1897 params.gradY = arguments[3 + extraArgs];
1898 extraArgs += 2;
1899 }
1900 //if (gather && compare) {
1901 // params.compare = arguments[2 + extraArgs];
1902 // ++extraArgs;
1903 //}
1904 if (cracked.offset || cracked.offsets) {
1905 params.offset = arguments[2 + extraArgs];
1906 ++extraArgs;
1907 }
1908 if (bias) {
1909 params.bias = arguments[2 + extraArgs];
1910 ++extraArgs;
1911 }
1912
Jason Ekstrand18b9fbd2015-09-05 14:14:48 -07001913 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001914}
1915
1916spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
1917{
1918 // Grab the function's pointer from the previously created function
1919 spv::Function* function = functionMap[node->getName().c_str()];
1920 if (! function)
1921 return 0;
1922
1923 const glslang::TIntermSequence& glslangArgs = node->getSequence();
1924 const glslang::TQualifierList& qualifiers = node->getQualifierList();
1925
1926 // See comments in makeFunctions() for details about the semantics for parameter passing.
1927 //
1928 // These imply we need a four step process:
1929 // 1. Evaluate the arguments
1930 // 2. Allocate and make copies of in, out, and inout arguments
1931 // 3. Make the call
1932 // 4. Copy back the results
1933
1934 // 1. Evaluate the arguments
1935 std::vector<spv::Builder::AccessChain> lValues;
1936 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06001937 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06001938 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1939 // build l-value
1940 builder.clearAccessChain();
1941 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001942 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001943 // keep outputs as l-values, evaluate input-only as r-values
1944 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1945 // save l-value
1946 lValues.push_back(builder.getAccessChain());
1947 } else {
1948 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06001949 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06001950 }
1951 }
1952
1953 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
1954 // copy the original into that space.
1955 //
1956 // Also, build up the list of actual arguments to pass in for the call
1957 int lValueCount = 0;
1958 int rValueCount = 0;
1959 std::vector<spv::Id> spvArgs;
1960 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1961 spv::Id arg;
1962 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1963 // need space to hold the copy
1964 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
1965 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
1966 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
1967 // need to copy the input into output space
1968 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06001969 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06001970 builder.createStore(copy, arg);
1971 }
1972 ++lValueCount;
1973 } else {
1974 arg = rValues[rValueCount];
1975 ++rValueCount;
1976 }
1977 spvArgs.push_back(arg);
1978 }
1979
1980 // 3. Make the call.
1981 spv::Id result = builder.createFunctionCall(function, spvArgs);
1982
1983 // 4. Copy back out an "out" arguments.
1984 lValueCount = 0;
1985 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1986 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1987 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
1988 spv::Id copy = builder.createLoad(spvArgs[a]);
1989 builder.setAccessChain(lValues[lValueCount]);
1990 builder.accessChainStore(copy);
1991 }
1992 ++lValueCount;
1993 }
1994 }
1995
1996 return result;
1997}
1998
1999// Translate AST operation to SPV operation, already having SPV-based operands/types.
2000spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2001 spv::Id typeId, spv::Id left, spv::Id right,
2002 glslang::TBasicType typeProxy, bool reduceComparison)
2003{
2004 bool isUnsigned = typeProxy == glslang::EbtUint;
2005 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2006
2007 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002008 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002009 bool comparison = false;
2010
2011 switch (op) {
2012 case glslang::EOpAdd:
2013 case glslang::EOpAddAssign:
2014 if (isFloat)
2015 binOp = spv::OpFAdd;
2016 else
2017 binOp = spv::OpIAdd;
2018 break;
2019 case glslang::EOpSub:
2020 case glslang::EOpSubAssign:
2021 if (isFloat)
2022 binOp = spv::OpFSub;
2023 else
2024 binOp = spv::OpISub;
2025 break;
2026 case glslang::EOpMul:
2027 case glslang::EOpMulAssign:
2028 if (isFloat)
2029 binOp = spv::OpFMul;
2030 else
2031 binOp = spv::OpIMul;
2032 break;
2033 case glslang::EOpVectorTimesScalar:
2034 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002035 if (isFloat) {
2036 if (builder.isVector(right))
2037 std::swap(left, right);
2038 assert(builder.isScalar(right));
2039 needMatchingVectors = false;
2040 binOp = spv::OpVectorTimesScalar;
2041 } else
2042 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002043 break;
2044 case glslang::EOpVectorTimesMatrix:
2045 case glslang::EOpVectorTimesMatrixAssign:
2046 assert(builder.isVector(left));
2047 assert(builder.isMatrix(right));
2048 binOp = spv::OpVectorTimesMatrix;
2049 break;
2050 case glslang::EOpMatrixTimesVector:
2051 assert(builder.isMatrix(left));
2052 assert(builder.isVector(right));
2053 binOp = spv::OpMatrixTimesVector;
2054 break;
2055 case glslang::EOpMatrixTimesScalar:
2056 case glslang::EOpMatrixTimesScalarAssign:
2057 if (builder.isMatrix(right))
2058 std::swap(left, right);
2059 assert(builder.isScalar(right));
2060 binOp = spv::OpMatrixTimesScalar;
2061 break;
2062 case glslang::EOpMatrixTimesMatrix:
2063 case glslang::EOpMatrixTimesMatrixAssign:
2064 assert(builder.isMatrix(left));
2065 assert(builder.isMatrix(right));
2066 binOp = spv::OpMatrixTimesMatrix;
2067 break;
2068 case glslang::EOpOuterProduct:
2069 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002070 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002071 break;
2072
2073 case glslang::EOpDiv:
2074 case glslang::EOpDivAssign:
2075 if (isFloat)
2076 binOp = spv::OpFDiv;
2077 else if (isUnsigned)
2078 binOp = spv::OpUDiv;
2079 else
2080 binOp = spv::OpSDiv;
2081 break;
2082 case glslang::EOpMod:
2083 case glslang::EOpModAssign:
2084 if (isFloat)
2085 binOp = spv::OpFMod;
2086 else if (isUnsigned)
2087 binOp = spv::OpUMod;
2088 else
2089 binOp = spv::OpSMod;
2090 break;
2091 case glslang::EOpRightShift:
2092 case glslang::EOpRightShiftAssign:
2093 if (isUnsigned)
2094 binOp = spv::OpShiftRightLogical;
2095 else
2096 binOp = spv::OpShiftRightArithmetic;
2097 break;
2098 case glslang::EOpLeftShift:
2099 case glslang::EOpLeftShiftAssign:
2100 binOp = spv::OpShiftLeftLogical;
2101 break;
2102 case glslang::EOpAnd:
2103 case glslang::EOpAndAssign:
2104 binOp = spv::OpBitwiseAnd;
2105 break;
2106 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002107 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002108 binOp = spv::OpLogicalAnd;
2109 break;
2110 case glslang::EOpInclusiveOr:
2111 case glslang::EOpInclusiveOrAssign:
2112 binOp = spv::OpBitwiseOr;
2113 break;
2114 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002115 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002116 binOp = spv::OpLogicalOr;
2117 break;
2118 case glslang::EOpExclusiveOr:
2119 case glslang::EOpExclusiveOrAssign:
2120 binOp = spv::OpBitwiseXor;
2121 break;
2122 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002123 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002124 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002125 break;
2126
2127 case glslang::EOpLessThan:
2128 case glslang::EOpGreaterThan:
2129 case glslang::EOpLessThanEqual:
2130 case glslang::EOpGreaterThanEqual:
2131 case glslang::EOpEqual:
2132 case glslang::EOpNotEqual:
2133 case glslang::EOpVectorEqual:
2134 case glslang::EOpVectorNotEqual:
2135 comparison = true;
2136 break;
2137 default:
2138 break;
2139 }
2140
2141 if (binOp != spv::OpNop) {
2142 if (builder.isMatrix(left) || builder.isMatrix(right)) {
2143 switch (binOp) {
2144 case spv::OpMatrixTimesScalar:
2145 case spv::OpVectorTimesMatrix:
2146 case spv::OpMatrixTimesVector:
2147 case spv::OpMatrixTimesMatrix:
2148 break;
2149 case spv::OpFDiv:
2150 // turn it into a multiply...
2151 assert(builder.isMatrix(left) && builder.isScalar(right));
2152 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2153 binOp = spv::OpFMul;
2154 break;
2155 default:
2156 spv::MissingFunctionality("binary operation on matrix");
2157 break;
2158 }
2159
2160 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2161 builder.setPrecision(id, precision);
2162
2163 return id;
2164 }
2165
2166 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002167 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002168 builder.promoteScalar(precision, left, right);
2169
2170 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2171 builder.setPrecision(id, precision);
2172
2173 return id;
2174 }
2175
2176 if (! comparison)
2177 return 0;
2178
2179 // Comparison instructions
2180
2181 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2182 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2183
2184 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
2185 }
2186
2187 switch (op) {
2188 case glslang::EOpLessThan:
2189 if (isFloat)
2190 binOp = spv::OpFOrdLessThan;
2191 else if (isUnsigned)
2192 binOp = spv::OpULessThan;
2193 else
2194 binOp = spv::OpSLessThan;
2195 break;
2196 case glslang::EOpGreaterThan:
2197 if (isFloat)
2198 binOp = spv::OpFOrdGreaterThan;
2199 else if (isUnsigned)
2200 binOp = spv::OpUGreaterThan;
2201 else
2202 binOp = spv::OpSGreaterThan;
2203 break;
2204 case glslang::EOpLessThanEqual:
2205 if (isFloat)
2206 binOp = spv::OpFOrdLessThanEqual;
2207 else if (isUnsigned)
2208 binOp = spv::OpULessThanEqual;
2209 else
2210 binOp = spv::OpSLessThanEqual;
2211 break;
2212 case glslang::EOpGreaterThanEqual:
2213 if (isFloat)
2214 binOp = spv::OpFOrdGreaterThanEqual;
2215 else if (isUnsigned)
2216 binOp = spv::OpUGreaterThanEqual;
2217 else
2218 binOp = spv::OpSGreaterThanEqual;
2219 break;
2220 case glslang::EOpEqual:
2221 case glslang::EOpVectorEqual:
2222 if (isFloat)
2223 binOp = spv::OpFOrdEqual;
2224 else
2225 binOp = spv::OpIEqual;
2226 break;
2227 case glslang::EOpNotEqual:
2228 case glslang::EOpVectorNotEqual:
2229 if (isFloat)
2230 binOp = spv::OpFOrdNotEqual;
2231 else
2232 binOp = spv::OpINotEqual;
2233 break;
2234 default:
2235 break;
2236 }
2237
2238 if (binOp != spv::OpNop) {
2239 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2240 builder.setPrecision(id, precision);
2241
2242 return id;
2243 }
2244
2245 return 0;
2246}
2247
Rex Xu04db3f52015-09-16 11:44:02 +08002248spv::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 -06002249{
2250 spv::Op unaryOp = spv::OpNop;
2251 int libCall = -1;
Rex Xu04db3f52015-09-16 11:44:02 +08002252 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002253
2254 switch (op) {
2255 case glslang::EOpNegative:
2256 if (isFloat)
2257 unaryOp = spv::OpFNegate;
2258 else
2259 unaryOp = spv::OpSNegate;
2260 break;
2261
2262 case glslang::EOpLogicalNot:
2263 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002264 unaryOp = spv::OpLogicalNot;
2265 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002266 case glslang::EOpBitwiseNot:
2267 unaryOp = spv::OpNot;
2268 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002269
John Kessenich140f3df2015-06-26 16:58:36 -06002270 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002271 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002272 break;
2273 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002274 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002275 break;
2276 case glslang::EOpTranspose:
2277 unaryOp = spv::OpTranspose;
2278 break;
2279
2280 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002281 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002282 break;
2283 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002284 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002285 break;
2286 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002287 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002288 break;
2289 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002290 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002291 break;
2292 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002293 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002294 break;
2295 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002296 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002297 break;
2298 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002299 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002300 break;
2301 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002302 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002303 break;
2304
2305 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002306 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002307 break;
2308 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002309 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002310 break;
2311 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002312 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002313 break;
2314 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002315 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002316 break;
2317 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002318 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002319 break;
2320 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002321 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002322 break;
2323
2324 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002325 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002326 break;
2327 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002328 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002329 break;
2330
2331 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002332 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002333 break;
2334 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002335 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002336 break;
2337 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002338 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002339 break;
2340 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002341 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002342 break;
2343 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002344 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002345 break;
2346 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002347 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002348 break;
2349
2350 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002351 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002352 break;
2353 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002354 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002355 break;
2356 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002357 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002358 break;
2359 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002360 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002361 break;
2362 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002363 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002364 break;
2365 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002366 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002367 break;
2368
2369 case glslang::EOpIsNan:
2370 unaryOp = spv::OpIsNan;
2371 break;
2372 case glslang::EOpIsInf:
2373 unaryOp = spv::OpIsInf;
2374 break;
2375
John Kessenich140f3df2015-06-26 16:58:36 -06002376 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002377 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002378 break;
2379 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002380 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002381 break;
2382 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002383 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002384 break;
2385 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002386 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002387 break;
2388 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002389 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002390 break;
2391 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002392 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002393 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002394 case glslang::EOpPackSnorm4x8:
2395 libCall = spv::GLSLstd450PackSnorm4x8;
2396 break;
2397 case glslang::EOpUnpackSnorm4x8:
2398 libCall = spv::GLSLstd450UnpackSnorm4x8;
2399 break;
2400 case glslang::EOpPackUnorm4x8:
2401 libCall = spv::GLSLstd450PackUnorm4x8;
2402 break;
2403 case glslang::EOpUnpackUnorm4x8:
2404 libCall = spv::GLSLstd450UnpackUnorm4x8;
2405 break;
2406 case glslang::EOpPackDouble2x32:
2407 libCall = spv::GLSLstd450PackDouble2x32;
2408 break;
2409 case glslang::EOpUnpackDouble2x32:
2410 libCall = spv::GLSLstd450UnpackDouble2x32;
2411 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002412
2413 case glslang::EOpDPdx:
2414 unaryOp = spv::OpDPdx;
2415 break;
2416 case glslang::EOpDPdy:
2417 unaryOp = spv::OpDPdy;
2418 break;
2419 case glslang::EOpFwidth:
2420 unaryOp = spv::OpFwidth;
2421 break;
2422 case glslang::EOpDPdxFine:
2423 unaryOp = spv::OpDPdxFine;
2424 break;
2425 case glslang::EOpDPdyFine:
2426 unaryOp = spv::OpDPdyFine;
2427 break;
2428 case glslang::EOpFwidthFine:
2429 unaryOp = spv::OpFwidthFine;
2430 break;
2431 case glslang::EOpDPdxCoarse:
2432 unaryOp = spv::OpDPdxCoarse;
2433 break;
2434 case glslang::EOpDPdyCoarse:
2435 unaryOp = spv::OpDPdyCoarse;
2436 break;
2437 case glslang::EOpFwidthCoarse:
2438 unaryOp = spv::OpFwidthCoarse;
2439 break;
2440
2441 case glslang::EOpAny:
2442 unaryOp = spv::OpAny;
2443 break;
2444 case glslang::EOpAll:
2445 unaryOp = spv::OpAll;
2446 break;
2447
2448 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002449 if (isFloat)
2450 libCall = spv::GLSLstd450FAbs;
2451 else
2452 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002453 break;
2454 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002455 if (isFloat)
2456 libCall = spv::GLSLstd450FSign;
2457 else
2458 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002459 break;
2460
John Kessenichfc51d282015-08-19 13:34:18 -06002461 case glslang::EOpAtomicCounterIncrement:
2462 case glslang::EOpAtomicCounterDecrement:
2463 case glslang::EOpAtomicCounter:
2464 {
2465 // Handle all of the atomics in one place, in createAtomicOperation()
2466 std::vector<spv::Id> operands;
2467 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002468 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002469 }
2470
2471 case glslang::EOpImageLoad:
2472 unaryOp = spv::OpImageRead;
2473 break;
2474
2475 case glslang::EOpBitFieldReverse:
2476 unaryOp = spv::OpBitReverse;
2477 break;
2478 case glslang::EOpBitCount:
2479 unaryOp = spv::OpBitCount;
2480 break;
2481 case glslang::EOpFindLSB:
2482 libCall = spv::GLSLstd450FindILSB;
2483 break;
2484 case glslang::EOpFindMSB:
2485 spv::MissingFunctionality("signed vs. unsigned FindMSB");
2486 libCall = spv::GLSLstd450FindSMSB;
2487 break;
2488
John Kessenich140f3df2015-06-26 16:58:36 -06002489 default:
2490 return 0;
2491 }
2492
2493 spv::Id id;
2494 if (libCall >= 0) {
2495 std::vector<spv::Id> args;
2496 args.push_back(operand);
2497 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2498 } else
2499 id = builder.createUnaryOp(unaryOp, typeId, operand);
2500
2501 builder.setPrecision(id, precision);
2502
2503 return id;
2504}
2505
2506spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2507{
2508 spv::Op convOp = spv::OpNop;
2509 spv::Id zero = 0;
2510 spv::Id one = 0;
2511
2512 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2513
2514 switch (op) {
2515 case glslang::EOpConvIntToBool:
2516 case glslang::EOpConvUintToBool:
2517 zero = builder.makeUintConstant(0);
2518 zero = makeSmearedConstant(zero, vectorSize);
2519 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2520
2521 case glslang::EOpConvFloatToBool:
2522 zero = builder.makeFloatConstant(0.0F);
2523 zero = makeSmearedConstant(zero, vectorSize);
2524 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2525
2526 case glslang::EOpConvDoubleToBool:
2527 zero = builder.makeDoubleConstant(0.0);
2528 zero = makeSmearedConstant(zero, vectorSize);
2529 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2530
2531 case glslang::EOpConvBoolToFloat:
2532 convOp = spv::OpSelect;
2533 zero = builder.makeFloatConstant(0.0);
2534 one = builder.makeFloatConstant(1.0);
2535 break;
2536 case glslang::EOpConvBoolToDouble:
2537 convOp = spv::OpSelect;
2538 zero = builder.makeDoubleConstant(0.0);
2539 one = builder.makeDoubleConstant(1.0);
2540 break;
2541 case glslang::EOpConvBoolToInt:
2542 zero = builder.makeIntConstant(0);
2543 one = builder.makeIntConstant(1);
2544 convOp = spv::OpSelect;
2545 break;
2546 case glslang::EOpConvBoolToUint:
2547 zero = builder.makeUintConstant(0);
2548 one = builder.makeUintConstant(1);
2549 convOp = spv::OpSelect;
2550 break;
2551
2552 case glslang::EOpConvIntToFloat:
2553 case glslang::EOpConvIntToDouble:
2554 convOp = spv::OpConvertSToF;
2555 break;
2556
2557 case glslang::EOpConvUintToFloat:
2558 case glslang::EOpConvUintToDouble:
2559 convOp = spv::OpConvertUToF;
2560 break;
2561
2562 case glslang::EOpConvDoubleToFloat:
2563 case glslang::EOpConvFloatToDouble:
2564 convOp = spv::OpFConvert;
2565 break;
2566
2567 case glslang::EOpConvFloatToInt:
2568 case glslang::EOpConvDoubleToInt:
2569 convOp = spv::OpConvertFToS;
2570 break;
2571
2572 case glslang::EOpConvUintToInt:
2573 case glslang::EOpConvIntToUint:
2574 convOp = spv::OpBitcast;
2575 break;
2576
2577 case glslang::EOpConvFloatToUint:
2578 case glslang::EOpConvDoubleToUint:
2579 convOp = spv::OpConvertFToU;
2580 break;
2581 default:
2582 break;
2583 }
2584
2585 spv::Id result = 0;
2586 if (convOp == spv::OpNop)
2587 return result;
2588
2589 if (convOp == spv::OpSelect) {
2590 zero = makeSmearedConstant(zero, vectorSize);
2591 one = makeSmearedConstant(one, vectorSize);
2592 result = builder.createTriOp(convOp, destType, operand, one, zero);
2593 } else
2594 result = builder.createUnaryOp(convOp, destType, operand);
2595
2596 builder.setPrecision(result, precision);
2597
2598 return result;
2599}
2600
2601spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2602{
2603 if (vectorSize == 0)
2604 return constant;
2605
2606 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2607 std::vector<spv::Id> components;
2608 for (int c = 0; c < vectorSize; ++c)
2609 components.push_back(constant);
2610 return builder.makeCompositeConstant(vectorTypeId, components);
2611}
2612
John Kessenich426394d2015-07-23 10:22:48 -06002613// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08002614spv::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 -06002615{
2616 spv::Op opCode = spv::OpNop;
2617
2618 switch (op) {
2619 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08002620 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06002621 opCode = spv::OpAtomicIAdd;
2622 break;
2623 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08002624 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08002625 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002626 break;
2627 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08002628 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08002629 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002630 break;
2631 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08002632 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06002633 opCode = spv::OpAtomicAnd;
2634 break;
2635 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08002636 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06002637 opCode = spv::OpAtomicOr;
2638 break;
2639 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08002640 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06002641 opCode = spv::OpAtomicXor;
2642 break;
2643 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08002644 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06002645 opCode = spv::OpAtomicExchange;
2646 break;
2647 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08002648 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06002649 opCode = spv::OpAtomicCompareExchange;
2650 break;
2651 case glslang::EOpAtomicCounterIncrement:
2652 opCode = spv::OpAtomicIIncrement;
2653 break;
2654 case glslang::EOpAtomicCounterDecrement:
2655 opCode = spv::OpAtomicIDecrement;
2656 break;
2657 case glslang::EOpAtomicCounter:
2658 opCode = spv::OpAtomicLoad;
2659 break;
2660 default:
2661 spv::MissingFunctionality("missing nested atomic");
2662 break;
2663 }
2664
2665 // Sort out the operands
2666 // - mapping from glslang -> SPV
2667 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06002668 // - compare-exchange swaps the value and comparator
2669 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06002670 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2671 auto opIt = operands.begin(); // walk the glslang operands
2672 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08002673 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2674 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
2675 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08002676 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
2677 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08002678 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06002679 spvAtomicOperands.push_back(*(opIt + 1));
2680 spvAtomicOperands.push_back(*opIt);
2681 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08002682 }
John Kessenich426394d2015-07-23 10:22:48 -06002683
John Kessenich3e60a6f2015-09-14 22:45:16 -06002684 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06002685 for (; opIt != operands.end(); ++opIt)
2686 spvAtomicOperands.push_back(*opIt);
2687
2688 return builder.createOp(opCode, typeId, spvAtomicOperands);
2689}
2690
John Kessenich5e4b1242015-08-06 22:53:06 -06002691spv::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 -06002692{
John Kessenich5e4b1242015-08-06 22:53:06 -06002693 bool isUnsigned = typeProxy == glslang::EbtUint;
2694 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2695
John Kessenich140f3df2015-06-26 16:58:36 -06002696 spv::Op opCode = spv::OpNop;
2697 int libCall = -1;
2698
2699 switch (op) {
2700 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002701 if (isFloat)
2702 libCall = spv::GLSLstd450FMin;
2703 else if (isUnsigned)
2704 libCall = spv::GLSLstd450UMin;
2705 else
2706 libCall = spv::GLSLstd450SMin;
John Kessenich140f3df2015-06-26 16:58:36 -06002707 break;
2708 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002709 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002710 break;
2711 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002712 if (isFloat)
2713 libCall = spv::GLSLstd450FMax;
2714 else if (isUnsigned)
2715 libCall = spv::GLSLstd450UMax;
2716 else
2717 libCall = spv::GLSLstd450SMax;
John Kessenich140f3df2015-06-26 16:58:36 -06002718 break;
2719 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002720 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002721 break;
2722 case glslang::EOpDot:
2723 opCode = spv::OpDot;
2724 break;
2725 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002726 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002727 break;
2728
2729 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002730 if (isFloat)
2731 libCall = spv::GLSLstd450FClamp;
2732 else if (isUnsigned)
2733 libCall = spv::GLSLstd450UClamp;
2734 else
2735 libCall = spv::GLSLstd450SClamp;
John Kessenich140f3df2015-06-26 16:58:36 -06002736 break;
2737 case glslang::EOpMix:
John Kessenich5e4b1242015-08-06 22:53:06 -06002738 libCall = spv::GLSLstd450Mix;
John Kessenich140f3df2015-06-26 16:58:36 -06002739 break;
2740 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002741 libCall = spv::GLSLstd450Step;
John Kessenich140f3df2015-06-26 16:58:36 -06002742 break;
2743 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002744 libCall = spv::GLSLstd450SmoothStep;
John Kessenich140f3df2015-06-26 16:58:36 -06002745 break;
2746
2747 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002748 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002749 break;
2750 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002751 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002752 break;
2753 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002754 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002755 break;
2756 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002757 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002758 break;
2759 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002760 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002761 break;
John Kessenich426394d2015-07-23 10:22:48 -06002762
John Kessenich140f3df2015-06-26 16:58:36 -06002763 default:
2764 return 0;
2765 }
2766
2767 spv::Id id = 0;
2768 if (libCall >= 0)
2769 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, operands);
2770 else {
2771 switch (operands.size()) {
2772 case 0:
2773 // should all be handled by visitAggregate and createNoArgOperation
2774 assert(0);
2775 return 0;
2776 case 1:
2777 // should all be handled by createUnaryOperation
2778 assert(0);
2779 return 0;
2780 case 2:
2781 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
2782 break;
2783 case 3:
John Kessenich426394d2015-07-23 10:22:48 -06002784 id = builder.createTriOp(opCode, typeId, operands[0], operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002785 break;
2786 default:
2787 // These do not exist yet
2788 assert(0 && "operation with more than 3 operands");
2789 break;
2790 }
2791 }
2792
2793 builder.setPrecision(id, precision);
2794
2795 return id;
2796}
2797
2798// Intrinsics with no arguments, no return value, and no precision.
2799spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
2800{
2801 // TODO: get the barrier operands correct
2802
2803 switch (op) {
2804 case glslang::EOpEmitVertex:
2805 builder.createNoResultOp(spv::OpEmitVertex);
2806 return 0;
2807 case glslang::EOpEndPrimitive:
2808 builder.createNoResultOp(spv::OpEndPrimitive);
2809 return 0;
2810 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002811 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
2812 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06002813 return 0;
2814 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002815 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06002816 return 0;
2817 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06002818 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002819 return 0;
2820 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06002821 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002822 return 0;
2823 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06002824 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002825 return 0;
2826 case glslang::EOpMemoryBarrierShared:
John Kessenich5e4b1242015-08-06 22:53:06 -06002827 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupLocalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002828 return 0;
2829 case glslang::EOpGroupMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002830 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupGlobalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002831 return 0;
2832 default:
2833 spv::MissingFunctionality("operation with no arguments");
2834 return 0;
2835 }
2836}
2837
2838spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
2839{
John Kessenich2f273362015-07-18 22:34:27 -06002840 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06002841 spv::Id id;
2842 if (symbolValues.end() != iter) {
2843 id = iter->second;
2844 return id;
2845 }
2846
2847 // it was not found, create it
2848 id = createSpvVariable(symbol);
2849 symbolValues[symbol->getId()] = id;
2850
2851 if (! symbol->getType().isStruct()) {
2852 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
2853 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
2854 if (symbol->getQualifier().hasLocation())
2855 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
2856 if (symbol->getQualifier().hasIndex())
2857 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
2858 if (symbol->getQualifier().hasComponent())
2859 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
2860 if (glslangIntermediate->getXfbMode()) {
2861 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002862 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002863 if (symbol->getQualifier().hasXfbBuffer())
2864 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2865 if (symbol->getQualifier().hasXfbOffset())
2866 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
2867 }
2868 }
2869
2870 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
2871 if (symbol->getQualifier().hasStream())
2872 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
2873 if (symbol->getQualifier().hasSet())
2874 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
2875 if (symbol->getQualifier().hasBinding())
2876 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
2877 if (glslangIntermediate->getXfbMode()) {
2878 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002879 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002880 if (symbol->getQualifier().hasXfbBuffer())
2881 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2882 }
2883
2884 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06002885 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06002886 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06002887 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06002888
2889 if (linkageOnly)
2890 builder.addDecoration(id, spv::DecorationNoStaticUse);
2891
2892 return id;
2893}
2894
2895void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
2896{
2897 if (dec != spv::BadValue)
2898 builder.addDecoration(id, dec);
2899}
2900
2901void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
2902{
2903 if (dec != spv::BadValue)
2904 builder.addMemberDecoration(id, (unsigned)member, dec);
2905}
2906
2907// Use 'consts' as the flattened glslang source of scalar constants to recursively
2908// build the aggregate SPIR-V constant.
2909//
2910// If there are not enough elements present in 'consts', 0 will be substituted;
2911// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
2912//
2913spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst)
2914{
2915 // vector of constants for SPIR-V
2916 std::vector<spv::Id> spvConsts;
2917
2918 // Type is used for struct and array constants
2919 spv::Id typeId = convertGlslangToSpvType(glslangType);
2920
2921 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002922 glslang::TType elementType(glslangType, 0);
2923 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich140f3df2015-06-26 16:58:36 -06002924 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst));
2925 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002926 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06002927 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
2928 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst));
2929 } else if (glslangType.getStruct()) {
2930 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
2931 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
2932 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst));
2933 } else if (glslangType.isVector()) {
2934 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
2935 bool zero = nextConst >= consts.size();
2936 switch (glslangType.getBasicType()) {
2937 case glslang::EbtInt:
2938 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
2939 break;
2940 case glslang::EbtUint:
2941 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
2942 break;
2943 case glslang::EbtFloat:
2944 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
2945 break;
2946 case glslang::EbtDouble:
2947 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
2948 break;
2949 case glslang::EbtBool:
2950 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
2951 break;
2952 default:
2953 spv::MissingFunctionality("constant vector type");
2954 break;
2955 }
2956 ++nextConst;
2957 }
2958 } else {
2959 // we have a non-aggregate (scalar) constant
2960 bool zero = nextConst >= consts.size();
2961 spv::Id scalar = 0;
2962 switch (glslangType.getBasicType()) {
2963 case glslang::EbtInt:
2964 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst());
2965 break;
2966 case glslang::EbtUint:
2967 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst());
2968 break;
2969 case glslang::EbtFloat:
2970 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst());
2971 break;
2972 case glslang::EbtDouble:
2973 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst());
2974 break;
2975 case glslang::EbtBool:
2976 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst());
2977 break;
2978 default:
2979 spv::MissingFunctionality("constant scalar type");
2980 break;
2981 }
2982 ++nextConst;
2983 return scalar;
2984 }
2985
2986 return builder.makeCompositeConstant(typeId, spvConsts);
2987}
2988
2989}; // end anonymous namespace
2990
2991namespace glslang {
2992
John Kessenich68d78fd2015-07-12 19:28:10 -06002993void GetSpirvVersion(std::string& version)
2994{
John Kessenich9e55f632015-07-15 10:03:39 -06002995 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06002996 char buf[bufSize];
John Kessenich9e55f632015-07-15 10:03:39 -06002997 snprintf(buf, bufSize, "%d, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06002998 version = buf;
2999}
3000
John Kessenich140f3df2015-06-26 16:58:36 -06003001// Write SPIR-V out to a binary file
3002void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3003{
3004 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003005 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003006 for (int i = 0; i < (int)spirv.size(); ++i) {
3007 unsigned int word = spirv[i];
3008 out.write((const char*)&word, 4);
3009 }
3010 out.close();
3011}
3012
3013//
3014// Set up the glslang traversal
3015//
3016void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3017{
3018 TIntermNode* root = intermediate.getTreeRoot();
3019
3020 if (root == 0)
3021 return;
3022
3023 glslang::GetThreadPoolAllocator().push();
3024
3025 TGlslangToSpvTraverser it(&intermediate);
3026
3027 root->traverse(&it);
3028
3029 it.dumpSpv(spirv);
3030
3031 glslang::GetThreadPoolAllocator().pop();
3032}
3033
3034}; // end namespace glslang