blob: f6f99a4f26750bd8d2cc02e9acfb25765b69d518 [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);
Jason Ekstrand54aedf12015-09-05 09:50:58 -070091 int getArrayStride(const glslang::TType& arrayType);
92 int getMatrixStride(const glslang::TType& matrixType);
John Kessenich5e4b1242015-08-06 22:53:06 -060093 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset);
John Kessenich140f3df2015-06-26 16:58:36 -060094
95 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
96 void makeFunctions(const glslang::TIntermSequence&);
97 void makeGlobalInitializers(const glslang::TIntermSequence&);
98 void visitFunctions(const glslang::TIntermSequence&);
99 void handleFunctionEntry(const glslang::TIntermAggregate* node);
100 void translateArguments(const glslang::TIntermSequence& glslangArguments, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600101 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
102 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600103 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
104
105 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
106 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, bool isFloat);
107 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
108 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich426394d2015-07-23 10:22:48 -0600109 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600110 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 -0600111 spv::Id createNoArgOperation(glslang::TOperator op);
112 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
113 void addDecoration(spv::Id id, spv::Decoration dec);
114 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
115 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst);
116
117 spv::Function* shaderEntry;
118 int sequenceDepth;
119
120 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
121 spv::Builder builder;
122 bool inMain;
123 bool mainTerminated;
124 bool linkageOnly;
125 const glslang::TIntermediate* glslangIntermediate;
126 spv::Id stdBuiltins;
127
John Kessenich2f273362015-07-18 22:34:27 -0600128 std::unordered_map<int, spv::Id> symbolValues;
129 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
130 std::unordered_map<std::string, spv::Function*> functionMap;
131 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap;
132 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 -0600133 std::stack<bool> breakForLoop; // false means break for switch
134 std::stack<glslang::TIntermTyped*> loopTerminal; // code from the last part of a for loop: for(...; ...; terminal), needed for e.g., continue };
135};
136
137//
138// Helper functions for translating glslang representations to SPIR-V enumerants.
139//
140
141// Translate glslang profile to SPIR-V source language.
142spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
143{
144 switch (profile) {
145 case ENoProfile:
146 case ECoreProfile:
147 case ECompatibilityProfile:
148 return spv::SourceLanguageGLSL;
149 case EEsProfile:
150 return spv::SourceLanguageESSL;
151 default:
152 return spv::SourceLanguageUnknown;
153 }
154}
155
156// Translate glslang language (stage) to SPIR-V execution model.
157spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
158{
159 switch (stage) {
160 case EShLangVertex: return spv::ExecutionModelVertex;
161 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
162 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
163 case EShLangGeometry: return spv::ExecutionModelGeometry;
164 case EShLangFragment: return spv::ExecutionModelFragment;
165 case EShLangCompute: return spv::ExecutionModelGLCompute;
166 default:
167 spv::MissingFunctionality("GLSL stage");
168 return spv::ExecutionModelFragment;
169 }
170}
171
172// Translate glslang type to SPIR-V storage class.
173spv::StorageClass TranslateStorageClass(const glslang::TType& type)
174{
175 if (type.getQualifier().isPipeInput())
176 return spv::StorageClassInput;
177 else if (type.getQualifier().isPipeOutput())
178 return spv::StorageClassOutput;
179 else if (type.getQualifier().isUniformOrBuffer()) {
180 if (type.getBasicType() == glslang::EbtBlock)
181 return spv::StorageClassUniform;
182 else
183 return spv::StorageClassUniformConstant;
184 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
185 } else {
186 switch (type.getQualifier().storage) {
187 case glslang::EvqShared: return spv::StorageClassWorkgroupLocal; break;
188 case glslang::EvqGlobal: return spv::StorageClassPrivateGlobal;
189 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
190 case glslang::EvqTemporary: return spv::StorageClassFunction;
191 default:
192 spv::MissingFunctionality("unknown glslang storage class");
193 return spv::StorageClassFunction;
194 }
195 }
196}
197
198// Translate glslang sampler type to SPIR-V dimensionality.
199spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
200{
201 switch (sampler.dim) {
202 case glslang::Esd1D: return spv::Dim1D;
203 case glslang::Esd2D: return spv::Dim2D;
204 case glslang::Esd3D: return spv::Dim3D;
205 case glslang::EsdCube: return spv::DimCube;
206 case glslang::EsdRect: return spv::DimRect;
207 case glslang::EsdBuffer: return spv::DimBuffer;
208 default:
209 spv::MissingFunctionality("unknown sampler dimension");
210 return spv::Dim2D;
211 }
212}
213
214// Translate glslang type to SPIR-V precision decorations.
215spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
216{
217 switch (type.getQualifier().precision) {
John Kessenich5e4b1242015-08-06 22:53:06 -0600218 case glslang::EpqLow: return spv::DecorationRelaxedPrecision; // TODO: Map instead to 16-bit types?
219 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
220 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600221 default:
222 return spv::NoPrecision;
223 }
224}
225
226// Translate glslang type to SPIR-V block decorations.
227spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
228{
229 if (type.getBasicType() == glslang::EbtBlock) {
230 switch (type.getQualifier().storage) {
231 case glslang::EvqUniform: return spv::DecorationBlock;
232 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
233 case glslang::EvqVaryingIn: return spv::DecorationBlock;
234 case glslang::EvqVaryingOut: return spv::DecorationBlock;
235 default:
236 spv::MissingFunctionality("kind of block");
237 break;
238 }
239 }
240
241 return (spv::Decoration)spv::BadValue;
242}
243
244// Translate glslang type to SPIR-V layout decorations.
245spv::Decoration TranslateLayoutDecoration(const glslang::TType& type)
246{
247 if (type.isMatrix()) {
248 switch (type.getQualifier().layoutMatrix) {
249 case glslang::ElmRowMajor:
250 return spv::DecorationRowMajor;
251 default:
252 return spv::DecorationColMajor;
253 }
254 } else {
255 switch (type.getBasicType()) {
256 default:
257 return (spv::Decoration)spv::BadValue;
258 break;
259 case glslang::EbtBlock:
260 switch (type.getQualifier().storage) {
261 case glslang::EvqUniform:
262 case glslang::EvqBuffer:
263 switch (type.getQualifier().layoutPacking) {
264 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
266 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600267 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600268 }
269 case glslang::EvqVaryingIn:
270 case glslang::EvqVaryingOut:
271 if (type.getQualifier().layoutPacking != glslang::ElpNone)
272 spv::MissingFunctionality("in/out block layout");
273 return (spv::Decoration)spv::BadValue;
274 default:
275 spv::MissingFunctionality("block storage qualification");
276 return (spv::Decoration)spv::BadValue;
277 }
278 }
279 }
280}
281
282// Translate glslang type to SPIR-V interpolation decorations.
283spv::Decoration TranslateInterpolationDecoration(const glslang::TType& type)
284{
285 if (type.getQualifier().smooth)
286 return spv::DecorationSmooth;
287 if (type.getQualifier().nopersp)
288 return spv::DecorationNoperspective;
289 else if (type.getQualifier().patch)
290 return spv::DecorationPatch;
291 else if (type.getQualifier().flat)
292 return spv::DecorationFlat;
293 else if (type.getQualifier().centroid)
294 return spv::DecorationCentroid;
295 else if (type.getQualifier().sample)
296 return spv::DecorationSample;
297 else
298 return (spv::Decoration)spv::BadValue;
299}
300
301// If glslang type is invaraiant, return SPIR-V invariant decoration.
302spv::Decoration TranslateInvariantDecoration(const glslang::TType& type)
303{
304 if (type.getQualifier().invariant)
305 return spv::DecorationInvariant;
306 else
307 return (spv::Decoration)spv::BadValue;
308}
309
310// Translate glslang built-in variable to SPIR-V built in decoration.
311spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
312{
313 switch (builtIn) {
314 case glslang::EbvPosition: return spv::BuiltInPosition;
315 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600316 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
317 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
318 case glslang::EbvVertexId: return spv::BuiltInVertexId;
319 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
320 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
321 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
322 case glslang::EbvLayer: return spv::BuiltInLayer;
323 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
324 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
325 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
326 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
327 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
328 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
329 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
330 case glslang::EbvFace: return spv::BuiltInFrontFacing;
331 case glslang::EbvSampleId: return spv::BuiltInSampleId;
332 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
333 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
334 case glslang::EbvFragColor: return spv::BuiltInFragColor;
335 case glslang::EbvFragData: return spv::BuiltInFragColor;
336 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
337 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
338 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
339 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
340 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
341 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
342 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
343 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
344 default: return (spv::BuiltIn)spv::BadValue;
345 }
346}
347
348//
349// Implement the TGlslangToSpvTraverser class.
350//
351
352TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
353 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
354 builder(GlslangMagic),
355 inMain(false), mainTerminated(false), linkageOnly(false),
356 glslangIntermediate(glslangIntermediate)
357{
358 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
359
360 builder.clearAccessChain();
361 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
362 stdBuiltins = builder.import("GLSL.std.450");
363 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
364 shaderEntry = builder.makeMain();
John Kessenich5e4b1242015-08-06 22:53:06 -0600365 builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600366
367 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600368 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
369 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600370 builder.addSourceExtension(it->c_str());
371
372 // Add the top-level modes for this shader.
373
374 if (glslangIntermediate->getXfbMode())
375 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
376
377 unsigned int mode;
378 switch (glslangIntermediate->getStage()) {
379 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600380 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600381 break;
382
383 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600384 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600385 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
386 break;
387
388 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600389 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600390 switch (glslangIntermediate->getInputPrimitive()) {
391 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
392 case glslang::ElgQuads: mode = spv::ExecutionModeInputQuads; break;
393 case glslang::ElgIsolines: mode = spv::ExecutionModeInputIsolines; break;
394 default: mode = spv::BadValue; break;
395 }
396 if (mode != spv::BadValue)
397 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
398
399 // TODO
400 //builder.addExecutionMode(spv::VertexSpacingMdName, glslangIntermediate->getVertexSpacing());
401 //builder.addExecutionMode(spv::VertexOrderMdName, glslangIntermediate->getVertexOrder());
402 //builder.addExecutionMode(spv::PointModeMdName, glslangIntermediate->getPointMode());
403 break;
404
405 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600406 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600407 switch (glslangIntermediate->getInputPrimitive()) {
408 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
409 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
410 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
411 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
412 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
413 default: mode = spv::BadValue; break;
414 }
415 if (mode != spv::BadValue)
416 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
417 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
418
419 switch (glslangIntermediate->getOutputPrimitive()) {
420 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
421 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
422 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
423 default: mode = spv::BadValue; break;
424 }
425 if (mode != spv::BadValue)
426 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
427 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
428 break;
429
430 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600431 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600432 if (glslangIntermediate->getPixelCenterInteger())
433 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
434 if (glslangIntermediate->getOriginUpperLeft())
435 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600436 else
437 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kessenich140f3df2015-06-26 16:58:36 -0600438 break;
439
440 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600441 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600442 break;
443
444 default:
445 break;
446 }
447
448}
449
450TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
451{
452 if (! mainTerminated) {
453 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
454 builder.setBuildPoint(lastMainBlock);
455 builder.leaveFunction(true);
456 }
457}
458
459//
460// Implement the traversal functions.
461//
462// Return true from interior nodes to have the external traversal
463// continue on to children. Return false if children were
464// already processed.
465//
466
467//
468// Symbols can turn into
469// - uniform/input reads
470// - output writes
471// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
472// - something simple that degenerates into the last bullet
473//
474void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
475{
476 // getSymbolId() will set up all the IO decorations on the first call.
477 // Formal function parameters were mapped during makeFunctions().
478 spv::Id id = getSymbolId(symbol);
479
480 if (! linkageOnly) {
481 // Prepare to generate code for the access
482
483 // L-value chains will be computed left to right. We're on the symbol now,
484 // which is the left-most part of the access chain, so now is "clear" time,
485 // followed by setting the base.
486 builder.clearAccessChain();
487
488 // For now, we consider all user variables as being in memory, so they are pointers,
489 // except for "const in" arguments to a function, which are an intermediate object.
490 // See comments in handleUserFunctionCall().
491 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
492 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
493 builder.setAccessChainRValue(id);
494 else
495 builder.setAccessChainLValue(id);
496 }
497}
498
499bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
500{
501 // First, handle special cases
502 switch (node->getOp()) {
503 case glslang::EOpAssign:
504 case glslang::EOpAddAssign:
505 case glslang::EOpSubAssign:
506 case glslang::EOpMulAssign:
507 case glslang::EOpVectorTimesMatrixAssign:
508 case glslang::EOpVectorTimesScalarAssign:
509 case glslang::EOpMatrixTimesScalarAssign:
510 case glslang::EOpMatrixTimesMatrixAssign:
511 case glslang::EOpDivAssign:
512 case glslang::EOpModAssign:
513 case glslang::EOpAndAssign:
514 case glslang::EOpInclusiveOrAssign:
515 case glslang::EOpExclusiveOrAssign:
516 case glslang::EOpLeftShiftAssign:
517 case glslang::EOpRightShiftAssign:
518 // A bin-op assign "a += b" means the same thing as "a = a + b"
519 // where a is evaluated before b. For a simple assignment, GLSL
520 // says to evaluate the left before the right. So, always, left
521 // node then right node.
522 {
523 // get the left l-value, save it away
524 builder.clearAccessChain();
525 node->getLeft()->traverse(this);
526 spv::Builder::AccessChain lValue = builder.getAccessChain();
527
528 // evaluate the right
529 builder.clearAccessChain();
530 node->getRight()->traverse(this);
531 spv::Id rValue = builder.accessChainLoad(TranslatePrecisionDecoration(node->getRight()->getType()));
532
533 if (node->getOp() != glslang::EOpAssign) {
534 // the left is also an r-value
535 builder.setAccessChain(lValue);
536 spv::Id leftRValue = builder.accessChainLoad(TranslatePrecisionDecoration(node->getLeft()->getType()));
537
538 // do the operation
539 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
540 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
541 node->getType().getBasicType());
542
543 // these all need their counterparts in createBinaryOperation()
544 if (rValue == 0)
545 spv::MissingFunctionality("createBinaryOperation");
546 }
547
548 // store the result
549 builder.setAccessChain(lValue);
550 builder.accessChainStore(rValue);
551
552 // assignments are expressions having an rValue after they are evaluated...
553 builder.clearAccessChain();
554 builder.setAccessChainRValue(rValue);
555 }
556 return false;
557 case glslang::EOpIndexDirect:
558 case glslang::EOpIndexDirectStruct:
559 {
560 // Get the left part of the access chain.
561 node->getLeft()->traverse(this);
562
563 // Add the next element in the chain
564
565 int index = 0;
566 if (node->getRight()->getAsConstantUnion() == 0)
567 spv::MissingFunctionality("direct index without a constant node");
568 else
569 index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
570
571 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
572 // This may be, e.g., an anonymous block-member selection, which generally need
573 // index remapping due to hidden members in anonymous blocks.
574 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
575 if (remapper.size() == 0)
576 spv::MissingFunctionality("block without member remapping");
577 else
578 index = remapper[index];
579 }
580
581 if (! node->getLeft()->getType().isArray() &&
582 node->getLeft()->getType().isVector() &&
583 node->getOp() == glslang::EOpIndexDirect) {
584 // This is essentially a hard-coded vector swizzle of size 1,
585 // so short circuit the access-chain stuff with a swizzle.
586 std::vector<unsigned> swizzle;
587 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
588 builder.accessChainPushSwizzle(swizzle);
589 } else {
590 // normal case for indexing array or structure or block
591 builder.accessChainPush(builder.makeIntConstant(index), convertGlslangToSpvType(node->getType()));
592 }
593 }
594 return false;
595 case glslang::EOpIndexIndirect:
596 {
597 // Structure or array or vector indirection.
598 // Will use native SPIR-V access-chain for struct and array indirection;
599 // matrices are arrays of vectors, so will also work for a matrix.
600 // Will use the access chain's 'component' for variable index into a vector.
601
602 // This adapter is building access chains left to right.
603 // Set up the access chain to the left.
604 node->getLeft()->traverse(this);
605
606 // save it so that computing the right side doesn't trash it
607 spv::Builder::AccessChain partial = builder.getAccessChain();
608
609 // compute the next index in the chain
610 builder.clearAccessChain();
611 node->getRight()->traverse(this);
612 spv::Id index = builder.accessChainLoad(TranslatePrecisionDecoration(node->getRight()->getType()));
613
614 // restore the saved access chain
615 builder.setAccessChain(partial);
616
617 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
618 builder.accessChainPushComponent(index);
619 else
620 builder.accessChainPush(index, convertGlslangToSpvType(node->getType()));
621 }
622 return false;
623 case glslang::EOpVectorSwizzle:
624 {
625 node->getLeft()->traverse(this);
626 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
627 std::vector<unsigned> swizzle;
628 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
629 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
630 builder.accessChainPushSwizzle(swizzle);
631 }
632 return false;
633 default:
634 break;
635 }
636
637 // Assume generic binary op...
638
639 // Get the operands
640 builder.clearAccessChain();
641 node->getLeft()->traverse(this);
642 spv::Id left = builder.accessChainLoad(TranslatePrecisionDecoration(node->getLeft()->getType()));
643
644 builder.clearAccessChain();
645 node->getRight()->traverse(this);
646 spv::Id right = builder.accessChainLoad(TranslatePrecisionDecoration(node->getRight()->getType()));
647
648 spv::Id result;
649 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
650
651 result = createBinaryOperation(node->getOp(), precision,
652 convertGlslangToSpvType(node->getType()), left, right,
653 node->getLeft()->getType().getBasicType());
654
655 if (! result) {
656 spv::MissingFunctionality("glslang binary operation");
657 } else {
658 builder.clearAccessChain();
659 builder.setAccessChainRValue(result);
660
661 return false;
662 }
663
664 return true;
665}
666
667bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
668{
John Kessenichfc51d282015-08-19 13:34:18 -0600669 spv::Id result = spv::NoResult;
670
671 // try texturing first
672 result = createImageTextureFunctionCall(node);
673 if (result != spv::NoResult) {
674 builder.clearAccessChain();
675 builder.setAccessChainRValue(result);
676
677 return false; // done with this node
678 }
679
680 // Non-texturing.
681 // Start by evaluating the operand
682
John Kessenich140f3df2015-06-26 16:58:36 -0600683 builder.clearAccessChain();
684 node->getOperand()->traverse(this);
685 spv::Id operand = builder.accessChainLoad(TranslatePrecisionDecoration(node->getOperand()->getType()));
686
687 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
688
689 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600690 if (! result)
691 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600692
693 // if not, then possibly an operation
694 if (! result)
John Kessenichfc51d282015-08-19 13:34:18 -0600695 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand,
696 node->getBasicType() == glslang::EbtFloat || node->getBasicType() == glslang::EbtDouble);
John Kessenich140f3df2015-06-26 16:58:36 -0600697
698 if (result) {
699 builder.clearAccessChain();
700 builder.setAccessChainRValue(result);
701
702 return false; // done with this node
703 }
704
705 // it must be a special case, check...
706 switch (node->getOp()) {
707 case glslang::EOpPostIncrement:
708 case glslang::EOpPostDecrement:
709 case glslang::EOpPreIncrement:
710 case glslang::EOpPreDecrement:
711 {
712 // we need the integer value "1" or the floating point "1.0" to add/subtract
713 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
714 builder.makeFloatConstant(1.0F) :
715 builder.makeIntConstant(1);
716 glslang::TOperator op;
717 if (node->getOp() == glslang::EOpPreIncrement ||
718 node->getOp() == glslang::EOpPostIncrement)
719 op = glslang::EOpAdd;
720 else
721 op = glslang::EOpSub;
722
723 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
724 convertGlslangToSpvType(node->getType()), operand, one,
725 node->getType().getBasicType());
726 if (result == 0)
727 spv::MissingFunctionality("createBinaryOperation for unary");
728
729 // The result of operation is always stored, but conditionally the
730 // consumed result. The consumed result is always an r-value.
731 builder.accessChainStore(result);
732 builder.clearAccessChain();
733 if (node->getOp() == glslang::EOpPreIncrement ||
734 node->getOp() == glslang::EOpPreDecrement)
735 builder.setAccessChainRValue(result);
736 else
737 builder.setAccessChainRValue(operand);
738 }
739
740 return false;
741
742 case glslang::EOpEmitStreamVertex:
743 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
744 return false;
745 case glslang::EOpEndStreamPrimitive:
746 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
747 return false;
748
749 default:
750 spv::MissingFunctionality("glslang unary");
751 break;
752 }
753
754 return true;
755}
756
757bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
758{
John Kessenichfc51d282015-08-19 13:34:18 -0600759 spv::Id result = spv::NoResult;
760
761 // try texturing
762 result = createImageTextureFunctionCall(node);
763 if (result != spv::NoResult) {
764 builder.clearAccessChain();
765 builder.setAccessChainRValue(result);
766
767 return false;
768 }
769
John Kessenich140f3df2015-06-26 16:58:36 -0600770 glslang::TOperator binOp = glslang::EOpNull;
771 bool reduceComparison = true;
772 bool isMatrix = false;
773 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600774 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600775
776 assert(node->getOp());
777
778 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
779
780 switch (node->getOp()) {
781 case glslang::EOpSequence:
782 {
783 if (preVisit)
784 ++sequenceDepth;
785 else
786 --sequenceDepth;
787
788 if (sequenceDepth == 1) {
789 // If this is the parent node of all the functions, we want to see them
790 // early, so all call points have actual SPIR-V functions to reference.
791 // In all cases, still let the traverser visit the children for us.
792 makeFunctions(node->getAsAggregate()->getSequence());
793
794 // Also, we want all globals initializers to go into the entry of main(), before
795 // anything else gets there, so visit out of order, doing them all now.
796 makeGlobalInitializers(node->getAsAggregate()->getSequence());
797
798 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
799 // so do them manually.
800 visitFunctions(node->getAsAggregate()->getSequence());
801
802 return false;
803 }
804
805 return true;
806 }
807 case glslang::EOpLinkerObjects:
808 {
809 if (visit == glslang::EvPreVisit)
810 linkageOnly = true;
811 else
812 linkageOnly = false;
813
814 return true;
815 }
816 case glslang::EOpComma:
817 {
818 // processing from left to right naturally leaves the right-most
819 // lying around in the access chain
820 glslang::TIntermSequence& glslangOperands = node->getSequence();
821 for (int i = 0; i < (int)glslangOperands.size(); ++i)
822 glslangOperands[i]->traverse(this);
823
824 return false;
825 }
826 case glslang::EOpFunction:
827 if (visit == glslang::EvPreVisit) {
828 if (isShaderEntrypoint(node)) {
829 inMain = true;
830 builder.setBuildPoint(shaderEntry->getLastBlock());
831 } else {
832 handleFunctionEntry(node);
833 }
834 } else {
835 if (inMain)
836 mainTerminated = true;
837 builder.leaveFunction(inMain);
838 inMain = false;
839 }
840
841 return true;
842 case glslang::EOpParameters:
843 // Parameters will have been consumed by EOpFunction processing, but not
844 // the body, so we still visited the function node's children, making this
845 // child redundant.
846 return false;
847 case glslang::EOpFunctionCall:
848 {
849 if (node->isUserDefined())
850 result = handleUserFunctionCall(node);
John Kessenich140f3df2015-06-26 16:58:36 -0600851
852 if (! result) {
853 spv::MissingFunctionality("glslang function call");
854 glslang::TConstUnionArray emptyConsts;
855 int nextConst = 0;
856 result = createSpvConstant(node->getType(), emptyConsts, nextConst);
857 }
858 builder.clearAccessChain();
859 builder.setAccessChainRValue(result);
860
861 return false;
862 }
863 case glslang::EOpConstructMat2x2:
864 case glslang::EOpConstructMat2x3:
865 case glslang::EOpConstructMat2x4:
866 case glslang::EOpConstructMat3x2:
867 case glslang::EOpConstructMat3x3:
868 case glslang::EOpConstructMat3x4:
869 case glslang::EOpConstructMat4x2:
870 case glslang::EOpConstructMat4x3:
871 case glslang::EOpConstructMat4x4:
872 case glslang::EOpConstructDMat2x2:
873 case glslang::EOpConstructDMat2x3:
874 case glslang::EOpConstructDMat2x4:
875 case glslang::EOpConstructDMat3x2:
876 case glslang::EOpConstructDMat3x3:
877 case glslang::EOpConstructDMat3x4:
878 case glslang::EOpConstructDMat4x2:
879 case glslang::EOpConstructDMat4x3:
880 case glslang::EOpConstructDMat4x4:
881 isMatrix = true;
882 // fall through
883 case glslang::EOpConstructFloat:
884 case glslang::EOpConstructVec2:
885 case glslang::EOpConstructVec3:
886 case glslang::EOpConstructVec4:
887 case glslang::EOpConstructDouble:
888 case glslang::EOpConstructDVec2:
889 case glslang::EOpConstructDVec3:
890 case glslang::EOpConstructDVec4:
891 case glslang::EOpConstructBool:
892 case glslang::EOpConstructBVec2:
893 case glslang::EOpConstructBVec3:
894 case glslang::EOpConstructBVec4:
895 case glslang::EOpConstructInt:
896 case glslang::EOpConstructIVec2:
897 case glslang::EOpConstructIVec3:
898 case glslang::EOpConstructIVec4:
899 case glslang::EOpConstructUint:
900 case glslang::EOpConstructUVec2:
901 case glslang::EOpConstructUVec3:
902 case glslang::EOpConstructUVec4:
903 case glslang::EOpConstructStruct:
904 {
905 std::vector<spv::Id> arguments;
906 translateArguments(node->getSequence(), arguments);
907 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
908 spv::Id constructed;
909 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
910 std::vector<spv::Id> constituents;
911 for (int c = 0; c < (int)arguments.size(); ++c)
912 constituents.push_back(arguments[c]);
913 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
914 } else {
915 if (isMatrix)
916 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
917 else
918 constructed = builder.createConstructor(precision, arguments, resultTypeId);
919 }
920
921 builder.clearAccessChain();
922 builder.setAccessChainRValue(constructed);
923
924 return false;
925 }
926
927 // These six are component-wise compares with component-wise results.
928 // Forward on to createBinaryOperation(), requesting a vector result.
929 case glslang::EOpLessThan:
930 case glslang::EOpGreaterThan:
931 case glslang::EOpLessThanEqual:
932 case glslang::EOpGreaterThanEqual:
933 case glslang::EOpVectorEqual:
934 case glslang::EOpVectorNotEqual:
935 {
936 // Map the operation to a binary
937 binOp = node->getOp();
938 reduceComparison = false;
939 switch (node->getOp()) {
940 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
941 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
942 default: binOp = node->getOp(); break;
943 }
944
945 break;
946 }
947 case glslang::EOpMul:
948 // compontent-wise matrix multiply
949 binOp = glslang::EOpMul;
950 break;
951 case glslang::EOpOuterProduct:
952 // two vectors multiplied to make a matrix
953 binOp = glslang::EOpOuterProduct;
954 break;
955 case glslang::EOpDot:
956 {
957 // for scalar dot product, use multiply
958 glslang::TIntermSequence& glslangOperands = node->getSequence();
959 if (! glslangOperands[0]->getAsTyped()->isVector())
960 binOp = glslang::EOpMul;
961 break;
962 }
963 case glslang::EOpMod:
964 // when an aggregate, this is the floating-point mod built-in function,
965 // which can be emitted by the one in createBinaryOperation()
966 binOp = glslang::EOpMod;
967 break;
968 case glslang::EOpArrayLength:
969 {
970 glslang::TIntermTyped* typedNode = node->getSequence()[0]->getAsTyped();
971 assert(typedNode);
John Kessenich65c78a02015-08-10 17:08:55 -0600972 spv::Id length = builder.makeIntConstant(typedNode->getType().getOuterArraySize());
John Kessenich140f3df2015-06-26 16:58:36 -0600973
974 builder.clearAccessChain();
975 builder.setAccessChainRValue(length);
976
977 return false;
978 }
979 case glslang::EOpEmitVertex:
980 case glslang::EOpEndPrimitive:
981 case glslang::EOpBarrier:
982 case glslang::EOpMemoryBarrier:
983 case glslang::EOpMemoryBarrierAtomicCounter:
984 case glslang::EOpMemoryBarrierBuffer:
985 case glslang::EOpMemoryBarrierImage:
986 case glslang::EOpMemoryBarrierShared:
987 case glslang::EOpGroupMemoryBarrier:
988 noReturnValue = true;
989 // These all have 0 operands and will naturally finish up in the code below for 0 operands
990 break;
991
John Kessenich426394d2015-07-23 10:22:48 -0600992 case glslang::EOpAtomicAdd:
993 case glslang::EOpAtomicMin:
994 case glslang::EOpAtomicMax:
995 case glslang::EOpAtomicAnd:
996 case glslang::EOpAtomicOr:
997 case glslang::EOpAtomicXor:
998 case glslang::EOpAtomicExchange:
999 case glslang::EOpAtomicCompSwap:
1000 atomic = true;
1001 break;
1002
John Kessenichfc51d282015-08-19 13:34:18 -06001003 case glslang::EOpAddCarry:
1004 case glslang::EOpSubBorrow:
1005 case glslang::EOpUMulExtended:
1006 case glslang::EOpIMulExtended:
1007 case glslang::EOpBitfieldExtract:
1008 case glslang::EOpBitfieldInsert:
1009 spv::MissingFunctionality("integer aggregate");
1010 break;
1011
1012 case glslang::EOpFma:
John Kessenich78258d32015-08-19 17:30:12 -06001013 case glslang::EOpFrexp:
1014 case glslang::EOpLdexp:
John Kessenichfc51d282015-08-19 13:34:18 -06001015 spv::MissingFunctionality("fma/frexp/ldexp aggregate");
1016 break;
1017
John Kessenich140f3df2015-06-26 16:58:36 -06001018 default:
1019 break;
1020 }
1021
1022 //
1023 // See if it maps to a regular operation.
1024 //
John Kessenich140f3df2015-06-26 16:58:36 -06001025 if (binOp != glslang::EOpNull) {
1026 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1027 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1028 assert(left && right);
1029
1030 builder.clearAccessChain();
1031 left->traverse(this);
1032 spv::Id leftId = builder.accessChainLoad(TranslatePrecisionDecoration(left->getType()));
1033
1034 builder.clearAccessChain();
1035 right->traverse(this);
1036 spv::Id rightId = builder.accessChainLoad(TranslatePrecisionDecoration(right->getType()));
1037
1038 result = createBinaryOperation(binOp, precision,
1039 convertGlslangToSpvType(node->getType()), leftId, rightId,
1040 left->getType().getBasicType(), reduceComparison);
1041
1042 // code above should only make binOp that exists in createBinaryOperation
1043 if (result == 0)
1044 spv::MissingFunctionality("createBinaryOperation for aggregate");
1045
1046 builder.clearAccessChain();
1047 builder.setAccessChainRValue(result);
1048
1049 return false;
1050 }
1051
John Kessenich426394d2015-07-23 10:22:48 -06001052 //
1053 // Create the list of operands.
1054 //
John Kessenich140f3df2015-06-26 16:58:36 -06001055 glslang::TIntermSequence& glslangOperands = node->getSequence();
1056 std::vector<spv::Id> operands;
1057 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1058 builder.clearAccessChain();
1059 glslangOperands[arg]->traverse(this);
1060
1061 // special case l-value operands; there are just a few
1062 bool lvalue = false;
1063 switch (node->getOp()) {
1064 //case glslang::EOpFrexp:
1065 case glslang::EOpModf:
1066 if (arg == 1)
1067 lvalue = true;
1068 break;
1069 //case glslang::EOpUAddCarry:
1070 //case glslang::EOpUSubBorrow:
1071 //case glslang::EOpUMulExtended:
1072 default:
1073 break;
1074 }
1075 if (lvalue)
1076 operands.push_back(builder.accessChainGetLValue());
1077 else
1078 operands.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangOperands[arg]->getAsTyped()->getType())));
1079 }
John Kessenich426394d2015-07-23 10:22:48 -06001080
1081 if (atomic) {
1082 // Handle all atomics
1083 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands);
1084 } else {
1085 // Pass through to generic operations.
1086 switch (glslangOperands.size()) {
1087 case 0:
1088 result = createNoArgOperation(node->getOp());
1089 break;
1090 case 1:
1091 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), node->getType().getBasicType() == glslang::EbtFloat || node->getType().getBasicType() == glslang::EbtDouble);
1092 break;
1093 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001094 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001095 break;
1096 }
John Kessenich140f3df2015-06-26 16:58:36 -06001097 }
1098
1099 if (noReturnValue)
1100 return false;
1101
1102 if (! result) {
1103 spv::MissingFunctionality("glslang aggregate");
1104 return true;
1105 } else {
1106 builder.clearAccessChain();
1107 builder.setAccessChainRValue(result);
1108 return false;
1109 }
1110}
1111
1112bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1113{
1114 // This path handles both if-then-else and ?:
1115 // The if-then-else has a node type of void, while
1116 // ?: has a non-void node type
1117 spv::Id result = 0;
1118 if (node->getBasicType() != glslang::EbtVoid) {
1119 // don't handle this as just on-the-fly temporaries, because there will be two names
1120 // and better to leave SSA to later passes
1121 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1122 }
1123
1124 // emit the condition before doing anything with selection
1125 node->getCondition()->traverse(this);
1126
1127 // make an "if" based on the value created by the condition
1128 spv::Builder::If ifBuilder(builder.accessChainLoad(spv::NoPrecision), builder);
1129
1130 if (node->getTrueBlock()) {
1131 // emit the "then" statement
1132 node->getTrueBlock()->traverse(this);
1133 if (result)
1134 builder.createStore(builder.accessChainLoad(TranslatePrecisionDecoration(node->getTrueBlock()->getAsTyped()->getType())), result);
1135 }
1136
1137 if (node->getFalseBlock()) {
1138 ifBuilder.makeBeginElse();
1139 // emit the "else" statement
1140 node->getFalseBlock()->traverse(this);
1141 if (result)
1142 builder.createStore(builder.accessChainLoad(TranslatePrecisionDecoration(node->getFalseBlock()->getAsTyped()->getType())), result);
1143 }
1144
1145 ifBuilder.makeEndIf();
1146
1147 if (result) {
1148 // GLSL only has r-values as the result of a :?, but
1149 // if we have an l-value, that can be more efficient if it will
1150 // become the base of a complex r-value expression, because the
1151 // next layer copies r-values into memory to use the access-chain mechanism
1152 builder.clearAccessChain();
1153 builder.setAccessChainLValue(result);
1154 }
1155
1156 return false;
1157}
1158
1159bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1160{
1161 // emit and get the condition before doing anything with switch
1162 node->getCondition()->traverse(this);
1163 spv::Id selector = builder.accessChainLoad(TranslatePrecisionDecoration(node->getCondition()->getAsTyped()->getType()));
1164
1165 // browse the children to sort out code segments
1166 int defaultSegment = -1;
1167 std::vector<TIntermNode*> codeSegments;
1168 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1169 std::vector<int> caseValues;
1170 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1171 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1172 TIntermNode* child = *c;
1173 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001174 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001175 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001176 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001177 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1178 } else
1179 codeSegments.push_back(child);
1180 }
1181
1182 // handle the case where the last code segment is missing, due to no code
1183 // statements between the last case and the end of the switch statement
1184 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1185 (int)codeSegments.size() == defaultSegment)
1186 codeSegments.push_back(nullptr);
1187
1188 // make the switch statement
1189 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001190 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001191
1192 // emit all the code in the segments
1193 breakForLoop.push(false);
1194 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1195 builder.nextSwitchSegment(segmentBlocks, s);
1196 if (codeSegments[s])
1197 codeSegments[s]->traverse(this);
1198 else
1199 builder.addSwitchBreak();
1200 }
1201 breakForLoop.pop();
1202
1203 builder.endSwitch(segmentBlocks);
1204
1205 return false;
1206}
1207
1208void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1209{
1210 int nextConst = 0;
1211 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1212
1213 builder.clearAccessChain();
1214 builder.setAccessChainRValue(constant);
1215}
1216
1217bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1218{
1219 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1220 loopTerminal.push(node->getTerminal());
1221
David Netoc22f37c2015-07-15 16:21:26 -04001222 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001223
1224 if (node->getTest()) {
1225 node->getTest()->traverse(this);
1226 // the AST only contained the test computation, not the branch, we have to add it
1227 spv::Id condition = builder.accessChainLoad(TranslatePrecisionDecoration(node->getTest()->getType()));
1228 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001229 } else {
1230 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001231 }
1232
David Netoc22f37c2015-07-15 16:21:26 -04001233 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001234 breakForLoop.push(true);
1235 node->getBody()->traverse(this);
1236 breakForLoop.pop();
1237 }
1238
1239 if (loopTerminal.top())
1240 loopTerminal.top()->traverse(this);
1241
1242 builder.closeLoop();
1243
1244 loopTerminal.pop();
1245
1246 return false;
1247}
1248
1249bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1250{
1251 if (node->getExpression())
1252 node->getExpression()->traverse(this);
1253
1254 switch (node->getFlowOp()) {
1255 case glslang::EOpKill:
1256 builder.makeDiscard();
1257 break;
1258 case glslang::EOpBreak:
1259 if (breakForLoop.top())
1260 builder.createLoopExit();
1261 else
1262 builder.addSwitchBreak();
1263 break;
1264 case glslang::EOpContinue:
1265 if (loopTerminal.top())
1266 loopTerminal.top()->traverse(this);
1267 builder.createLoopContinue();
1268 break;
1269 case glslang::EOpReturn:
1270 if (inMain)
1271 builder.makeMainReturn();
1272 else if (node->getExpression())
1273 builder.makeReturn(false, builder.accessChainLoad(TranslatePrecisionDecoration(node->getExpression()->getType())));
1274 else
1275 builder.makeReturn();
1276
1277 builder.clearAccessChain();
1278 break;
1279
1280 default:
1281 spv::MissingFunctionality("branch type");
1282 break;
1283 }
1284
1285 return false;
1286}
1287
1288spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1289{
1290 // First, steer off constants, which are not SPIR-V variables, but
1291 // can still have a mapping to a SPIR-V Id.
1292 if (node->getQualifier().storage == glslang::EvqConst) {
1293 int nextConst = 0;
1294 return createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1295 }
1296
1297 // Now, handle actual variables
1298 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1299 spv::Id spvType = convertGlslangToSpvType(node->getType());
1300
1301 const char* name = node->getName().c_str();
1302 if (glslang::IsAnonymous(name))
1303 name = "";
1304
1305 return builder.createVariable(storageClass, spvType, name);
1306}
1307
1308// Return type Id of the sampled type.
1309spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1310{
1311 switch (sampler.type) {
1312 case glslang::EbtFloat: return builder.makeFloatType(32);
1313 case glslang::EbtInt: return builder.makeIntType(32);
1314 case glslang::EbtUint: return builder.makeUintType(32);
1315 default:
1316 spv::MissingFunctionality("sampled type");
1317 return builder.makeFloatType(32);
1318 }
1319}
1320
1321// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1322spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1323{
1324 spv::Id spvType = 0;
1325
1326 switch (type.getBasicType()) {
1327 case glslang::EbtVoid:
1328 spvType = builder.makeVoidType();
1329 if (type.isArray())
1330 spv::MissingFunctionality("array of void");
1331 break;
1332 case glslang::EbtFloat:
1333 spvType = builder.makeFloatType(32);
1334 break;
1335 case glslang::EbtDouble:
1336 spvType = builder.makeFloatType(64);
1337 break;
1338 case glslang::EbtBool:
1339 spvType = builder.makeBoolType();
1340 break;
1341 case glslang::EbtInt:
1342 spvType = builder.makeIntType(32);
1343 break;
1344 case glslang::EbtUint:
1345 spvType = builder.makeUintType(32);
1346 break;
John Kessenich426394d2015-07-23 10:22:48 -06001347 case glslang::EbtAtomicUint:
1348 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1349 spvType = builder.makeUintType(32);
1350 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001351 case glslang::EbtSampler:
1352 {
1353 const glslang::TSampler& sampler = type.getSampler();
John Kessenich5e4b1242015-08-06 22:53:06 -06001354 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1355 sampler.image ? 2 : 1, spv::ImageFormatUnknown); // TODO: translate format, needed for GLSL image ops
1356 // OpenGL "textures" need to be combined with a sampler
1357 if (! sampler.image)
1358 spvType = builder.makeSampledImageType(spvType);
John Kessenich140f3df2015-06-26 16:58:36 -06001359 }
1360 break;
1361 case glslang::EbtStruct:
1362 case glslang::EbtBlock:
1363 {
1364 // If we've seen this struct type, return it
1365 const glslang::TTypeList* glslangStruct = type.getStruct();
1366 std::vector<spv::Id> structFields;
1367 spvType = structMap[glslangStruct];
1368 if (spvType)
1369 break;
1370
1371 // else, we haven't seen it...
1372
1373 // Create a vector of struct types for SPIR-V to consume
1374 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1375 if (type.getBasicType() == glslang::EbtBlock)
1376 memberRemapper[glslangStruct].resize(glslangStruct->size());
1377 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1378 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1379 if (glslangType.hiddenMember()) {
1380 ++memberDelta;
1381 if (type.getBasicType() == glslang::EbtBlock)
1382 memberRemapper[glslangStruct][i] = -1;
1383 } else {
1384 if (type.getBasicType() == glslang::EbtBlock)
1385 memberRemapper[glslangStruct][i] = i - memberDelta;
1386 structFields.push_back(convertGlslangToSpvType(glslangType));
1387 }
1388 }
1389
1390 // Make the SPIR-V type
1391 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
1392 structMap[glslangStruct] = spvType;
1393
1394 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001395 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001396 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1397 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1398 int member = i;
1399 if (type.getBasicType() == glslang::EbtBlock)
1400 member = memberRemapper[glslangStruct][i];
1401 // using -1 above to indicate a hidden member
1402 if (member >= 0) {
1403 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
1404 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType));
1405 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1406 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1407 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1408 if (glslangType.getQualifier().hasLocation())
1409 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1410 if (glslangType.getQualifier().hasComponent())
1411 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1412 if (glslangType.getQualifier().hasXfbOffset())
1413 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001414 else {
1415 // figure out what to do with offset, which is accumulating
1416 int nextOffset;
1417 updateMemberOffset(type, glslangType, offset, nextOffset);
1418 if (offset >= 0)
1419 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutOffset);
1420 offset = nextOffset;
1421 }
John Kessenich140f3df2015-06-26 16:58:36 -06001422
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001423 if (glslangType.isMatrix()) {
1424 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType));
1425 }
1426
John Kessenich140f3df2015-06-26 16:58:36 -06001427 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001428 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1429 if (builtIn != spv::BadValue)
1430 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001431 }
1432 }
1433
1434 // Decorate the structure
1435 addDecoration(spvType, TranslateLayoutDecoration(type));
1436 addDecoration(spvType, TranslateBlockDecoration(type));
1437 if (type.getQualifier().hasStream())
1438 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1439 if (glslangIntermediate->getXfbMode()) {
1440 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001441 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001442 if (type.getQualifier().hasXfbBuffer())
1443 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1444 }
1445 }
1446 break;
1447 default:
1448 spv::MissingFunctionality("basic type");
1449 break;
1450 }
1451
1452 if (type.isMatrix())
1453 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1454 else {
1455 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1456 if (type.getVectorSize() > 1)
1457 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1458 }
1459
1460 if (type.isArray()) {
1461 unsigned arraySize;
1462 if (! type.isExplicitlySizedArray()) {
1463 spv::MissingFunctionality("Unsized array");
1464 arraySize = 8;
1465 } else
John Kessenich65c78a02015-08-10 17:08:55 -06001466 arraySize = type.getOuterArraySize();
John Kessenich140f3df2015-06-26 16:58:36 -06001467 spvType = builder.makeArrayType(spvType, arraySize);
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001468 builder.addDecoration(spvType, spv::DecorationArrayStride, getArrayStride(type));
John Kessenich140f3df2015-06-26 16:58:36 -06001469 }
1470
1471 return spvType;
1472}
1473
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001474// Given an array type, returns the integer stride required for that array
1475int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType)
1476{
1477 glslang::TType derefType(arrayType, 0);
1478 int size;
1479 glslangIntermediate->getBaseAlignment(derefType, size, true);
1480 return size;
1481}
1482
1483// Given a matrix type, returns the integer stride required for that matrix
1484// when used as a member of an interface block
1485int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType)
1486{
1487 int size;
1488 return glslangIntermediate->getBaseAlignment(matrixType, size, true);
1489}
1490
John Kessenich5e4b1242015-08-06 22:53:06 -06001491// Given a member type of a struct, realign the current offset for it, and compute
1492// the next (not yet aligned) offset for the next member, which will get aligned
1493// on the next call.
1494// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1495// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1496// -1 means a non-forced member offset (no decoration needed).
1497void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset)
1498{
1499 // this will get a positive value when deemed necessary
1500 nextOffset = -1;
1501
1502 bool forceOffset = structType.getQualifier().layoutPacking == glslang::ElpStd140 ||
1503 structType.getQualifier().layoutPacking == glslang::ElpStd430;
1504
1505 // override anything in currentOffset with user-set offset
1506 if (memberType.getQualifier().hasOffset())
1507 currentOffset = memberType.getQualifier().layoutOffset;
1508
1509 // It could be that current linker usage in glslang updated all the layoutOffset,
1510 // in which case the following code does not matter. But, that's not quite right
1511 // once cross-compilation unit GLSL validation is done, as the original user
1512 // settings are needed in layoutOffset, and then the following will come into play.
1513
1514 if (! forceOffset) {
1515 if (! memberType.getQualifier().hasOffset())
1516 currentOffset = -1;
1517
1518 return;
1519 }
1520
1521 // Getting this far means we are forcing offsets
1522 if (currentOffset < 0)
1523 currentOffset = 0;
1524
1525 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1526 // but possibly not yet correctly aligned.
1527
1528 int memberSize;
1529 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, memberType.getQualifier().layoutPacking == glslang::ElpStd140);
1530 glslang::RoundToPow2(currentOffset, memberAlignment);
1531 nextOffset = currentOffset + memberSize;
1532}
1533
John Kessenich140f3df2015-06-26 16:58:36 -06001534bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1535{
1536 return node->getName() == "main(";
1537}
1538
1539// Make all the functions, skeletally, without actually visiting their bodies.
1540void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1541{
1542 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1543 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1544 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1545 continue;
1546
1547 // We're on a user function. Set up the basic interface for the function now,
1548 // so that it's available to call.
1549 // Translating the body will happen later.
1550 //
1551 // Typically (except for a "const in" parameter), an address will be passed to the
1552 // function. What it is an address of varies:
1553 //
1554 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1555 // so that write needs to be to a copy, hence the address of a copy works.
1556 //
1557 // - "const in" parameters can just be the r-value, as no writes need occur.
1558 //
1559 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1560 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1561
1562 std::vector<spv::Id> paramTypes;
1563 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1564
1565 for (int p = 0; p < (int)parameters.size(); ++p) {
1566 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1567 spv::Id typeId = convertGlslangToSpvType(paramType);
1568 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1569 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1570 else
1571 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1572 paramTypes.push_back(typeId);
1573 }
1574
1575 spv::Block* functionBlock;
1576 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1577 paramTypes, &functionBlock);
1578
1579 // Track function to emit/call later
1580 functionMap[glslFunction->getName().c_str()] = function;
1581
1582 // Set the parameter id's
1583 for (int p = 0; p < (int)parameters.size(); ++p) {
1584 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1585 // give a name too
1586 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1587 }
1588 }
1589}
1590
1591// Process all the initializers, while skipping the functions and link objects
1592void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1593{
1594 builder.setBuildPoint(shaderEntry->getLastBlock());
1595 for (int i = 0; i < (int)initializers.size(); ++i) {
1596 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1597 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1598
1599 // We're on a top-level node that's not a function. Treat as an initializer, whose
1600 // code goes into the beginning of main.
1601 initializer->traverse(this);
1602 }
1603 }
1604}
1605
1606// Process all the functions, while skipping initializers.
1607void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1608{
1609 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1610 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1611 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1612 node->traverse(this);
1613 }
1614}
1615
1616void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1617{
1618 // SPIR-V functions should already be in the functionMap from the prepass
1619 // that called makeFunctions().
1620 spv::Function* function = functionMap[node->getName().c_str()];
1621 spv::Block* functionBlock = function->getEntryBlock();
1622 builder.setBuildPoint(functionBlock);
1623}
1624
1625void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermSequence& glslangArguments, std::vector<spv::Id>& arguments)
1626{
1627 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1628 builder.clearAccessChain();
1629 glslangArguments[i]->traverse(this);
1630 arguments.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangArguments[i]->getAsTyped()->getType())));
1631 }
1632}
1633
John Kessenichfc51d282015-08-19 13:34:18 -06001634void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001635{
John Kessenichfc51d282015-08-19 13:34:18 -06001636 builder.clearAccessChain();
1637 node.getOperand()->traverse(this);
1638 arguments.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(node.getAsTyped()->getType())));
1639}
John Kessenich140f3df2015-06-26 16:58:36 -06001640
John Kessenichfc51d282015-08-19 13:34:18 -06001641spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1642{
1643 if (node->isImage()) {
1644 spv::MissingFunctionality("GLSL image function");
1645 return spv::NoResult;
1646 } else if (! node->isTexture()) {
1647 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001648 }
1649
John Kessenichfc51d282015-08-19 13:34:18 -06001650 // Process a GLSL texturing op (will be SPV image)
John Kessenich140f3df2015-06-26 16:58:36 -06001651
John Kessenichfc51d282015-08-19 13:34:18 -06001652 glslang::TCrackedTextureOp cracked;
1653 node->crackTexture(cracked);
1654
1655 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1656 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1657 std::vector<spv::Id> arguments;
1658 if (node->getAsAggregate())
1659 translateArguments(node->getAsAggregate()->getSequence(), arguments);
1660 else
1661 translateArguments(*node->getAsUnaryNode(), arguments);
1662 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1663
1664 spv::Builder::TextureParameters params = { };
1665 params.sampler = arguments[0];
1666
1667 // Check for queries
1668 if (cracked.query) {
1669 switch (node->getOp()) {
1670 case glslang::EOpImageQuerySize:
1671 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001672 if (arguments.size() > 1) {
1673 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001674 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001675 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001676 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001677 case glslang::EOpImageQuerySamples:
1678 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001679 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001680 case glslang::EOpTextureQueryLod:
1681 params.coords = arguments[1];
1682 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1683 case glslang::EOpTextureQueryLevels:
1684 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1685 default:
1686 assert(0);
1687 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001688 }
John Kessenich140f3df2015-06-26 16:58:36 -06001689 }
1690
John Kessenichfc51d282015-08-19 13:34:18 -06001691 // This is no longer a query....
John Kessenich140f3df2015-06-26 16:58:36 -06001692
John Kessenichfc51d282015-08-19 13:34:18 -06001693 if (cracked.gather)
1694 spv::MissingFunctionality("texture gather");
1695
1696 // check for bias argument
1697 bool bias = false;
1698 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch) {
1699 int nonBiasArgCount = 2;
1700 if (cracked.offset)
1701 ++nonBiasArgCount;
1702 if (cracked.grad)
1703 nonBiasArgCount += 2;
1704
1705 if ((int)arguments.size() > nonBiasArgCount)
1706 bias = true;
1707 }
1708
1709 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1710
1711 // set the rest of the arguments
1712 params.coords = arguments[1];
1713 int extraArgs = 0;
1714 if (cubeCompare)
1715 params.Dref = arguments[2];
1716 else if (sampler.shadow) {
1717 std::vector<spv::Id> indexes;
1718 int comp;
1719 if (cracked.proj)
1720 comp = 3;
1721 else
1722 comp = builder.getNumComponents(params.coords) - 1;
1723 indexes.push_back(comp);
1724 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1725 }
1726 if (cracked.lod) {
1727 params.lod = arguments[2];
1728 ++extraArgs;
1729 }
1730 if (cracked.grad) {
1731 params.gradX = arguments[2 + extraArgs];
1732 params.gradY = arguments[3 + extraArgs];
1733 extraArgs += 2;
1734 }
1735 //if (gather && compare) {
1736 // params.compare = arguments[2 + extraArgs];
1737 // ++extraArgs;
1738 //}
1739 if (cracked.offset || cracked.offsets) {
1740 params.offset = arguments[2 + extraArgs];
1741 ++extraArgs;
1742 }
1743 if (bias) {
1744 params.bias = arguments[2 + extraArgs];
1745 ++extraArgs;
1746 }
1747
Jason Ekstrand18b9fbd2015-09-05 14:14:48 -07001748 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001749}
1750
1751spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
1752{
1753 // Grab the function's pointer from the previously created function
1754 spv::Function* function = functionMap[node->getName().c_str()];
1755 if (! function)
1756 return 0;
1757
1758 const glslang::TIntermSequence& glslangArgs = node->getSequence();
1759 const glslang::TQualifierList& qualifiers = node->getQualifierList();
1760
1761 // See comments in makeFunctions() for details about the semantics for parameter passing.
1762 //
1763 // These imply we need a four step process:
1764 // 1. Evaluate the arguments
1765 // 2. Allocate and make copies of in, out, and inout arguments
1766 // 3. Make the call
1767 // 4. Copy back the results
1768
1769 // 1. Evaluate the arguments
1770 std::vector<spv::Builder::AccessChain> lValues;
1771 std::vector<spv::Id> rValues;
1772 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1773 // build l-value
1774 builder.clearAccessChain();
1775 glslangArgs[a]->traverse(this);
1776 // keep outputs as l-values, evaluate input-only as r-values
1777 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1778 // save l-value
1779 lValues.push_back(builder.getAccessChain());
1780 } else {
1781 // process r-value
1782 rValues.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangArgs[a]->getAsTyped()->getType())));
1783 }
1784 }
1785
1786 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
1787 // copy the original into that space.
1788 //
1789 // Also, build up the list of actual arguments to pass in for the call
1790 int lValueCount = 0;
1791 int rValueCount = 0;
1792 std::vector<spv::Id> spvArgs;
1793 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1794 spv::Id arg;
1795 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1796 // need space to hold the copy
1797 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
1798 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
1799 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
1800 // need to copy the input into output space
1801 builder.setAccessChain(lValues[lValueCount]);
1802 spv::Id copy = builder.accessChainLoad(spv::NoPrecision); // TODO: get precision
1803 builder.createStore(copy, arg);
1804 }
1805 ++lValueCount;
1806 } else {
1807 arg = rValues[rValueCount];
1808 ++rValueCount;
1809 }
1810 spvArgs.push_back(arg);
1811 }
1812
1813 // 3. Make the call.
1814 spv::Id result = builder.createFunctionCall(function, spvArgs);
1815
1816 // 4. Copy back out an "out" arguments.
1817 lValueCount = 0;
1818 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1819 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1820 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
1821 spv::Id copy = builder.createLoad(spvArgs[a]);
1822 builder.setAccessChain(lValues[lValueCount]);
1823 builder.accessChainStore(copy);
1824 }
1825 ++lValueCount;
1826 }
1827 }
1828
1829 return result;
1830}
1831
1832// Translate AST operation to SPV operation, already having SPV-based operands/types.
1833spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
1834 spv::Id typeId, spv::Id left, spv::Id right,
1835 glslang::TBasicType typeProxy, bool reduceComparison)
1836{
1837 bool isUnsigned = typeProxy == glslang::EbtUint;
1838 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
1839
1840 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06001841 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06001842 bool comparison = false;
1843
1844 switch (op) {
1845 case glslang::EOpAdd:
1846 case glslang::EOpAddAssign:
1847 if (isFloat)
1848 binOp = spv::OpFAdd;
1849 else
1850 binOp = spv::OpIAdd;
1851 break;
1852 case glslang::EOpSub:
1853 case glslang::EOpSubAssign:
1854 if (isFloat)
1855 binOp = spv::OpFSub;
1856 else
1857 binOp = spv::OpISub;
1858 break;
1859 case glslang::EOpMul:
1860 case glslang::EOpMulAssign:
1861 if (isFloat)
1862 binOp = spv::OpFMul;
1863 else
1864 binOp = spv::OpIMul;
1865 break;
1866 case glslang::EOpVectorTimesScalar:
1867 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06001868 if (isFloat) {
1869 if (builder.isVector(right))
1870 std::swap(left, right);
1871 assert(builder.isScalar(right));
1872 needMatchingVectors = false;
1873 binOp = spv::OpVectorTimesScalar;
1874 } else
1875 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06001876 break;
1877 case glslang::EOpVectorTimesMatrix:
1878 case glslang::EOpVectorTimesMatrixAssign:
1879 assert(builder.isVector(left));
1880 assert(builder.isMatrix(right));
1881 binOp = spv::OpVectorTimesMatrix;
1882 break;
1883 case glslang::EOpMatrixTimesVector:
1884 assert(builder.isMatrix(left));
1885 assert(builder.isVector(right));
1886 binOp = spv::OpMatrixTimesVector;
1887 break;
1888 case glslang::EOpMatrixTimesScalar:
1889 case glslang::EOpMatrixTimesScalarAssign:
1890 if (builder.isMatrix(right))
1891 std::swap(left, right);
1892 assert(builder.isScalar(right));
1893 binOp = spv::OpMatrixTimesScalar;
1894 break;
1895 case glslang::EOpMatrixTimesMatrix:
1896 case glslang::EOpMatrixTimesMatrixAssign:
1897 assert(builder.isMatrix(left));
1898 assert(builder.isMatrix(right));
1899 binOp = spv::OpMatrixTimesMatrix;
1900 break;
1901 case glslang::EOpOuterProduct:
1902 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06001903 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001904 break;
1905
1906 case glslang::EOpDiv:
1907 case glslang::EOpDivAssign:
1908 if (isFloat)
1909 binOp = spv::OpFDiv;
1910 else if (isUnsigned)
1911 binOp = spv::OpUDiv;
1912 else
1913 binOp = spv::OpSDiv;
1914 break;
1915 case glslang::EOpMod:
1916 case glslang::EOpModAssign:
1917 if (isFloat)
1918 binOp = spv::OpFMod;
1919 else if (isUnsigned)
1920 binOp = spv::OpUMod;
1921 else
1922 binOp = spv::OpSMod;
1923 break;
1924 case glslang::EOpRightShift:
1925 case glslang::EOpRightShiftAssign:
1926 if (isUnsigned)
1927 binOp = spv::OpShiftRightLogical;
1928 else
1929 binOp = spv::OpShiftRightArithmetic;
1930 break;
1931 case glslang::EOpLeftShift:
1932 case glslang::EOpLeftShiftAssign:
1933 binOp = spv::OpShiftLeftLogical;
1934 break;
1935 case glslang::EOpAnd:
1936 case glslang::EOpAndAssign:
1937 binOp = spv::OpBitwiseAnd;
1938 break;
1939 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06001940 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001941 binOp = spv::OpLogicalAnd;
1942 break;
1943 case glslang::EOpInclusiveOr:
1944 case glslang::EOpInclusiveOrAssign:
1945 binOp = spv::OpBitwiseOr;
1946 break;
1947 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06001948 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001949 binOp = spv::OpLogicalOr;
1950 break;
1951 case glslang::EOpExclusiveOr:
1952 case glslang::EOpExclusiveOrAssign:
1953 binOp = spv::OpBitwiseXor;
1954 break;
1955 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06001956 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06001957 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06001958 break;
1959
1960 case glslang::EOpLessThan:
1961 case glslang::EOpGreaterThan:
1962 case glslang::EOpLessThanEqual:
1963 case glslang::EOpGreaterThanEqual:
1964 case glslang::EOpEqual:
1965 case glslang::EOpNotEqual:
1966 case glslang::EOpVectorEqual:
1967 case glslang::EOpVectorNotEqual:
1968 comparison = true;
1969 break;
1970 default:
1971 break;
1972 }
1973
1974 if (binOp != spv::OpNop) {
1975 if (builder.isMatrix(left) || builder.isMatrix(right)) {
1976 switch (binOp) {
1977 case spv::OpMatrixTimesScalar:
1978 case spv::OpVectorTimesMatrix:
1979 case spv::OpMatrixTimesVector:
1980 case spv::OpMatrixTimesMatrix:
1981 break;
1982 case spv::OpFDiv:
1983 // turn it into a multiply...
1984 assert(builder.isMatrix(left) && builder.isScalar(right));
1985 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
1986 binOp = spv::OpFMul;
1987 break;
1988 default:
1989 spv::MissingFunctionality("binary operation on matrix");
1990 break;
1991 }
1992
1993 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
1994 builder.setPrecision(id, precision);
1995
1996 return id;
1997 }
1998
1999 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002000 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002001 builder.promoteScalar(precision, left, right);
2002
2003 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2004 builder.setPrecision(id, precision);
2005
2006 return id;
2007 }
2008
2009 if (! comparison)
2010 return 0;
2011
2012 // Comparison instructions
2013
2014 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2015 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2016
2017 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
2018 }
2019
2020 switch (op) {
2021 case glslang::EOpLessThan:
2022 if (isFloat)
2023 binOp = spv::OpFOrdLessThan;
2024 else if (isUnsigned)
2025 binOp = spv::OpULessThan;
2026 else
2027 binOp = spv::OpSLessThan;
2028 break;
2029 case glslang::EOpGreaterThan:
2030 if (isFloat)
2031 binOp = spv::OpFOrdGreaterThan;
2032 else if (isUnsigned)
2033 binOp = spv::OpUGreaterThan;
2034 else
2035 binOp = spv::OpSGreaterThan;
2036 break;
2037 case glslang::EOpLessThanEqual:
2038 if (isFloat)
2039 binOp = spv::OpFOrdLessThanEqual;
2040 else if (isUnsigned)
2041 binOp = spv::OpULessThanEqual;
2042 else
2043 binOp = spv::OpSLessThanEqual;
2044 break;
2045 case glslang::EOpGreaterThanEqual:
2046 if (isFloat)
2047 binOp = spv::OpFOrdGreaterThanEqual;
2048 else if (isUnsigned)
2049 binOp = spv::OpUGreaterThanEqual;
2050 else
2051 binOp = spv::OpSGreaterThanEqual;
2052 break;
2053 case glslang::EOpEqual:
2054 case glslang::EOpVectorEqual:
2055 if (isFloat)
2056 binOp = spv::OpFOrdEqual;
2057 else
2058 binOp = spv::OpIEqual;
2059 break;
2060 case glslang::EOpNotEqual:
2061 case glslang::EOpVectorNotEqual:
2062 if (isFloat)
2063 binOp = spv::OpFOrdNotEqual;
2064 else
2065 binOp = spv::OpINotEqual;
2066 break;
2067 default:
2068 break;
2069 }
2070
2071 if (binOp != spv::OpNop) {
2072 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2073 builder.setPrecision(id, precision);
2074
2075 return id;
2076 }
2077
2078 return 0;
2079}
2080
2081spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, bool isFloat)
2082{
2083 spv::Op unaryOp = spv::OpNop;
2084 int libCall = -1;
2085
2086 switch (op) {
2087 case glslang::EOpNegative:
2088 if (isFloat)
2089 unaryOp = spv::OpFNegate;
2090 else
2091 unaryOp = spv::OpSNegate;
2092 break;
2093
2094 case glslang::EOpLogicalNot:
2095 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002096 unaryOp = spv::OpLogicalNot;
2097 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002098 case glslang::EOpBitwiseNot:
2099 unaryOp = spv::OpNot;
2100 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002101
John Kessenich140f3df2015-06-26 16:58:36 -06002102 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002103 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002104 break;
2105 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002106 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002107 break;
2108 case glslang::EOpTranspose:
2109 unaryOp = spv::OpTranspose;
2110 break;
2111
2112 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002113 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002114 break;
2115 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002116 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002117 break;
2118 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002119 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002120 break;
2121 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002122 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002123 break;
2124 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002125 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002126 break;
2127 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002128 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002129 break;
2130 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002131 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002132 break;
2133 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002134 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002135 break;
2136
2137 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002138 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002139 break;
2140 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002141 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002142 break;
2143 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002144 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002145 break;
2146 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002147 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002148 break;
2149 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002150 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002151 break;
2152 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002153 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002154 break;
2155
2156 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002157 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002158 break;
2159 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002160 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002161 break;
2162
2163 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002164 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002165 break;
2166 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002167 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002168 break;
2169 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002170 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002171 break;
2172 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002173 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002174 break;
2175 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002176 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002177 break;
2178 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002179 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002180 break;
2181
2182 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002183 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002184 break;
2185 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002186 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002187 break;
2188 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002189 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002190 break;
2191 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002192 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002193 break;
2194 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002195 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002196 break;
2197 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002198 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002199 break;
2200
2201 case glslang::EOpIsNan:
2202 unaryOp = spv::OpIsNan;
2203 break;
2204 case glslang::EOpIsInf:
2205 unaryOp = spv::OpIsInf;
2206 break;
2207
John Kessenich140f3df2015-06-26 16:58:36 -06002208 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002209 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002210 break;
2211 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002212 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002213 break;
2214 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002215 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002216 break;
2217 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002218 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002219 break;
2220 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002221 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002222 break;
2223 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002224 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002225 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002226 case glslang::EOpPackSnorm4x8:
2227 libCall = spv::GLSLstd450PackSnorm4x8;
2228 break;
2229 case glslang::EOpUnpackSnorm4x8:
2230 libCall = spv::GLSLstd450UnpackSnorm4x8;
2231 break;
2232 case glslang::EOpPackUnorm4x8:
2233 libCall = spv::GLSLstd450PackUnorm4x8;
2234 break;
2235 case glslang::EOpUnpackUnorm4x8:
2236 libCall = spv::GLSLstd450UnpackUnorm4x8;
2237 break;
2238 case glslang::EOpPackDouble2x32:
2239 libCall = spv::GLSLstd450PackDouble2x32;
2240 break;
2241 case glslang::EOpUnpackDouble2x32:
2242 libCall = spv::GLSLstd450UnpackDouble2x32;
2243 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002244
2245 case glslang::EOpDPdx:
2246 unaryOp = spv::OpDPdx;
2247 break;
2248 case glslang::EOpDPdy:
2249 unaryOp = spv::OpDPdy;
2250 break;
2251 case glslang::EOpFwidth:
2252 unaryOp = spv::OpFwidth;
2253 break;
2254 case glslang::EOpDPdxFine:
2255 unaryOp = spv::OpDPdxFine;
2256 break;
2257 case glslang::EOpDPdyFine:
2258 unaryOp = spv::OpDPdyFine;
2259 break;
2260 case glslang::EOpFwidthFine:
2261 unaryOp = spv::OpFwidthFine;
2262 break;
2263 case glslang::EOpDPdxCoarse:
2264 unaryOp = spv::OpDPdxCoarse;
2265 break;
2266 case glslang::EOpDPdyCoarse:
2267 unaryOp = spv::OpDPdyCoarse;
2268 break;
2269 case glslang::EOpFwidthCoarse:
2270 unaryOp = spv::OpFwidthCoarse;
2271 break;
2272
2273 case glslang::EOpAny:
2274 unaryOp = spv::OpAny;
2275 break;
2276 case glslang::EOpAll:
2277 unaryOp = spv::OpAll;
2278 break;
2279
2280 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002281 if (isFloat)
2282 libCall = spv::GLSLstd450FAbs;
2283 else
2284 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002285 break;
2286 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002287 if (isFloat)
2288 libCall = spv::GLSLstd450FSign;
2289 else
2290 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002291 break;
2292
John Kessenichfc51d282015-08-19 13:34:18 -06002293 case glslang::EOpAtomicCounterIncrement:
2294 case glslang::EOpAtomicCounterDecrement:
2295 case glslang::EOpAtomicCounter:
2296 {
2297 // Handle all of the atomics in one place, in createAtomicOperation()
2298 std::vector<spv::Id> operands;
2299 operands.push_back(operand);
2300 return createAtomicOperation(op, precision, typeId, operands);
2301 }
2302
2303 case glslang::EOpImageLoad:
2304 unaryOp = spv::OpImageRead;
2305 break;
2306
2307 case glslang::EOpBitFieldReverse:
2308 unaryOp = spv::OpBitReverse;
2309 break;
2310 case glslang::EOpBitCount:
2311 unaryOp = spv::OpBitCount;
2312 break;
2313 case glslang::EOpFindLSB:
2314 libCall = spv::GLSLstd450FindILSB;
2315 break;
2316 case glslang::EOpFindMSB:
2317 spv::MissingFunctionality("signed vs. unsigned FindMSB");
2318 libCall = spv::GLSLstd450FindSMSB;
2319 break;
2320
John Kessenich140f3df2015-06-26 16:58:36 -06002321 default:
2322 return 0;
2323 }
2324
2325 spv::Id id;
2326 if (libCall >= 0) {
2327 std::vector<spv::Id> args;
2328 args.push_back(operand);
2329 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2330 } else
2331 id = builder.createUnaryOp(unaryOp, typeId, operand);
2332
2333 builder.setPrecision(id, precision);
2334
2335 return id;
2336}
2337
2338spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2339{
2340 spv::Op convOp = spv::OpNop;
2341 spv::Id zero = 0;
2342 spv::Id one = 0;
2343
2344 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2345
2346 switch (op) {
2347 case glslang::EOpConvIntToBool:
2348 case glslang::EOpConvUintToBool:
2349 zero = builder.makeUintConstant(0);
2350 zero = makeSmearedConstant(zero, vectorSize);
2351 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2352
2353 case glslang::EOpConvFloatToBool:
2354 zero = builder.makeFloatConstant(0.0F);
2355 zero = makeSmearedConstant(zero, vectorSize);
2356 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2357
2358 case glslang::EOpConvDoubleToBool:
2359 zero = builder.makeDoubleConstant(0.0);
2360 zero = makeSmearedConstant(zero, vectorSize);
2361 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2362
2363 case glslang::EOpConvBoolToFloat:
2364 convOp = spv::OpSelect;
2365 zero = builder.makeFloatConstant(0.0);
2366 one = builder.makeFloatConstant(1.0);
2367 break;
2368 case glslang::EOpConvBoolToDouble:
2369 convOp = spv::OpSelect;
2370 zero = builder.makeDoubleConstant(0.0);
2371 one = builder.makeDoubleConstant(1.0);
2372 break;
2373 case glslang::EOpConvBoolToInt:
2374 zero = builder.makeIntConstant(0);
2375 one = builder.makeIntConstant(1);
2376 convOp = spv::OpSelect;
2377 break;
2378 case glslang::EOpConvBoolToUint:
2379 zero = builder.makeUintConstant(0);
2380 one = builder.makeUintConstant(1);
2381 convOp = spv::OpSelect;
2382 break;
2383
2384 case glslang::EOpConvIntToFloat:
2385 case glslang::EOpConvIntToDouble:
2386 convOp = spv::OpConvertSToF;
2387 break;
2388
2389 case glslang::EOpConvUintToFloat:
2390 case glslang::EOpConvUintToDouble:
2391 convOp = spv::OpConvertUToF;
2392 break;
2393
2394 case glslang::EOpConvDoubleToFloat:
2395 case glslang::EOpConvFloatToDouble:
2396 convOp = spv::OpFConvert;
2397 break;
2398
2399 case glslang::EOpConvFloatToInt:
2400 case glslang::EOpConvDoubleToInt:
2401 convOp = spv::OpConvertFToS;
2402 break;
2403
2404 case glslang::EOpConvUintToInt:
2405 case glslang::EOpConvIntToUint:
2406 convOp = spv::OpBitcast;
2407 break;
2408
2409 case glslang::EOpConvFloatToUint:
2410 case glslang::EOpConvDoubleToUint:
2411 convOp = spv::OpConvertFToU;
2412 break;
2413 default:
2414 break;
2415 }
2416
2417 spv::Id result = 0;
2418 if (convOp == spv::OpNop)
2419 return result;
2420
2421 if (convOp == spv::OpSelect) {
2422 zero = makeSmearedConstant(zero, vectorSize);
2423 one = makeSmearedConstant(one, vectorSize);
2424 result = builder.createTriOp(convOp, destType, operand, one, zero);
2425 } else
2426 result = builder.createUnaryOp(convOp, destType, operand);
2427
2428 builder.setPrecision(result, precision);
2429
2430 return result;
2431}
2432
2433spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2434{
2435 if (vectorSize == 0)
2436 return constant;
2437
2438 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2439 std::vector<spv::Id> components;
2440 for (int c = 0; c < vectorSize; ++c)
2441 components.push_back(constant);
2442 return builder.makeCompositeConstant(vectorTypeId, components);
2443}
2444
John Kessenich426394d2015-07-23 10:22:48 -06002445// For glslang ops that map to SPV atomic opCodes
2446spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands)
2447{
2448 spv::Op opCode = spv::OpNop;
2449
2450 switch (op) {
2451 case glslang::EOpAtomicAdd:
2452 opCode = spv::OpAtomicIAdd;
2453 break;
2454 case glslang::EOpAtomicMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002455 opCode = spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002456 break;
2457 case glslang::EOpAtomicMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002458 opCode = spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002459 break;
2460 case glslang::EOpAtomicAnd:
2461 opCode = spv::OpAtomicAnd;
2462 break;
2463 case glslang::EOpAtomicOr:
2464 opCode = spv::OpAtomicOr;
2465 break;
2466 case glslang::EOpAtomicXor:
2467 opCode = spv::OpAtomicXor;
2468 break;
2469 case glslang::EOpAtomicExchange:
2470 opCode = spv::OpAtomicExchange;
2471 break;
2472 case glslang::EOpAtomicCompSwap:
2473 opCode = spv::OpAtomicCompareExchange;
2474 break;
2475 case glslang::EOpAtomicCounterIncrement:
2476 opCode = spv::OpAtomicIIncrement;
2477 break;
2478 case glslang::EOpAtomicCounterDecrement:
2479 opCode = spv::OpAtomicIDecrement;
2480 break;
2481 case glslang::EOpAtomicCounter:
2482 opCode = spv::OpAtomicLoad;
2483 break;
2484 default:
2485 spv::MissingFunctionality("missing nested atomic");
2486 break;
2487 }
2488
2489 // Sort out the operands
2490 // - mapping from glslang -> SPV
2491 // - there are extra SPV operands with no glslang source
2492 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2493 auto opIt = operands.begin(); // walk the glslang operands
2494 spvAtomicOperands.push_back(*(opIt++));
John Kessenich5e4b1242015-08-06 22:53:06 -06002495 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2496 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
John Kessenich426394d2015-07-23 10:22:48 -06002497
2498 // Add the rest of the operands, skipping the first one, which was dealt with above.
2499 // For some ops, there are none, for some 1, for compare-exchange, 2.
2500 for (; opIt != operands.end(); ++opIt)
2501 spvAtomicOperands.push_back(*opIt);
2502
2503 return builder.createOp(opCode, typeId, spvAtomicOperands);
2504}
2505
John Kessenich5e4b1242015-08-06 22:53:06 -06002506spv::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 -06002507{
John Kessenich5e4b1242015-08-06 22:53:06 -06002508 bool isUnsigned = typeProxy == glslang::EbtUint;
2509 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2510
John Kessenich140f3df2015-06-26 16:58:36 -06002511 spv::Op opCode = spv::OpNop;
2512 int libCall = -1;
2513
2514 switch (op) {
2515 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002516 if (isFloat)
2517 libCall = spv::GLSLstd450FMin;
2518 else if (isUnsigned)
2519 libCall = spv::GLSLstd450UMin;
2520 else
2521 libCall = spv::GLSLstd450SMin;
John Kessenich140f3df2015-06-26 16:58:36 -06002522 break;
2523 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002524 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002525 break;
2526 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002527 if (isFloat)
2528 libCall = spv::GLSLstd450FMax;
2529 else if (isUnsigned)
2530 libCall = spv::GLSLstd450UMax;
2531 else
2532 libCall = spv::GLSLstd450SMax;
John Kessenich140f3df2015-06-26 16:58:36 -06002533 break;
2534 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002535 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002536 break;
2537 case glslang::EOpDot:
2538 opCode = spv::OpDot;
2539 break;
2540 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002541 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002542 break;
2543
2544 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002545 if (isFloat)
2546 libCall = spv::GLSLstd450FClamp;
2547 else if (isUnsigned)
2548 libCall = spv::GLSLstd450UClamp;
2549 else
2550 libCall = spv::GLSLstd450SClamp;
John Kessenich140f3df2015-06-26 16:58:36 -06002551 break;
2552 case glslang::EOpMix:
John Kessenich5e4b1242015-08-06 22:53:06 -06002553 libCall = spv::GLSLstd450Mix;
John Kessenich140f3df2015-06-26 16:58:36 -06002554 break;
2555 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002556 libCall = spv::GLSLstd450Step;
John Kessenich140f3df2015-06-26 16:58:36 -06002557 break;
2558 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002559 libCall = spv::GLSLstd450SmoothStep;
John Kessenich140f3df2015-06-26 16:58:36 -06002560 break;
2561
2562 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002563 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002564 break;
2565 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002566 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002567 break;
2568 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002569 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002570 break;
2571 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002572 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002573 break;
2574 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002575 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002576 break;
John Kessenich426394d2015-07-23 10:22:48 -06002577
John Kessenich140f3df2015-06-26 16:58:36 -06002578 default:
2579 return 0;
2580 }
2581
2582 spv::Id id = 0;
2583 if (libCall >= 0)
2584 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, operands);
2585 else {
2586 switch (operands.size()) {
2587 case 0:
2588 // should all be handled by visitAggregate and createNoArgOperation
2589 assert(0);
2590 return 0;
2591 case 1:
2592 // should all be handled by createUnaryOperation
2593 assert(0);
2594 return 0;
2595 case 2:
2596 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
2597 break;
2598 case 3:
John Kessenich426394d2015-07-23 10:22:48 -06002599 id = builder.createTriOp(opCode, typeId, operands[0], operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002600 break;
2601 default:
2602 // These do not exist yet
2603 assert(0 && "operation with more than 3 operands");
2604 break;
2605 }
2606 }
2607
2608 builder.setPrecision(id, precision);
2609
2610 return id;
2611}
2612
2613// Intrinsics with no arguments, no return value, and no precision.
2614spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
2615{
2616 // TODO: get the barrier operands correct
2617
2618 switch (op) {
2619 case glslang::EOpEmitVertex:
2620 builder.createNoResultOp(spv::OpEmitVertex);
2621 return 0;
2622 case glslang::EOpEndPrimitive:
2623 builder.createNoResultOp(spv::OpEndPrimitive);
2624 return 0;
2625 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002626 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
2627 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06002628 return 0;
2629 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002630 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06002631 return 0;
2632 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06002633 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002634 return 0;
2635 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06002636 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002637 return 0;
2638 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06002639 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002640 return 0;
2641 case glslang::EOpMemoryBarrierShared:
John Kessenich5e4b1242015-08-06 22:53:06 -06002642 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupLocalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002643 return 0;
2644 case glslang::EOpGroupMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002645 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupGlobalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002646 return 0;
2647 default:
2648 spv::MissingFunctionality("operation with no arguments");
2649 return 0;
2650 }
2651}
2652
2653spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
2654{
John Kessenich2f273362015-07-18 22:34:27 -06002655 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06002656 spv::Id id;
2657 if (symbolValues.end() != iter) {
2658 id = iter->second;
2659 return id;
2660 }
2661
2662 // it was not found, create it
2663 id = createSpvVariable(symbol);
2664 symbolValues[symbol->getId()] = id;
2665
2666 if (! symbol->getType().isStruct()) {
2667 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
2668 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
2669 if (symbol->getQualifier().hasLocation())
2670 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
2671 if (symbol->getQualifier().hasIndex())
2672 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
2673 if (symbol->getQualifier().hasComponent())
2674 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
2675 if (glslangIntermediate->getXfbMode()) {
2676 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002677 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002678 if (symbol->getQualifier().hasXfbBuffer())
2679 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2680 if (symbol->getQualifier().hasXfbOffset())
2681 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
2682 }
2683 }
2684
2685 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
2686 if (symbol->getQualifier().hasStream())
2687 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
2688 if (symbol->getQualifier().hasSet())
2689 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
2690 if (symbol->getQualifier().hasBinding())
2691 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
2692 if (glslangIntermediate->getXfbMode()) {
2693 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002694 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002695 if (symbol->getQualifier().hasXfbBuffer())
2696 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2697 }
2698
2699 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06002700 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06002701 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06002702 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06002703
2704 if (linkageOnly)
2705 builder.addDecoration(id, spv::DecorationNoStaticUse);
2706
2707 return id;
2708}
2709
2710void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
2711{
2712 if (dec != spv::BadValue)
2713 builder.addDecoration(id, dec);
2714}
2715
2716void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
2717{
2718 if (dec != spv::BadValue)
2719 builder.addMemberDecoration(id, (unsigned)member, dec);
2720}
2721
2722// Use 'consts' as the flattened glslang source of scalar constants to recursively
2723// build the aggregate SPIR-V constant.
2724//
2725// If there are not enough elements present in 'consts', 0 will be substituted;
2726// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
2727//
2728spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst)
2729{
2730 // vector of constants for SPIR-V
2731 std::vector<spv::Id> spvConsts;
2732
2733 // Type is used for struct and array constants
2734 spv::Id typeId = convertGlslangToSpvType(glslangType);
2735
2736 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002737 glslang::TType elementType(glslangType, 0);
2738 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich140f3df2015-06-26 16:58:36 -06002739 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst));
2740 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002741 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06002742 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
2743 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst));
2744 } else if (glslangType.getStruct()) {
2745 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
2746 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
2747 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst));
2748 } else if (glslangType.isVector()) {
2749 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
2750 bool zero = nextConst >= consts.size();
2751 switch (glslangType.getBasicType()) {
2752 case glslang::EbtInt:
2753 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
2754 break;
2755 case glslang::EbtUint:
2756 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
2757 break;
2758 case glslang::EbtFloat:
2759 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
2760 break;
2761 case glslang::EbtDouble:
2762 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
2763 break;
2764 case glslang::EbtBool:
2765 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
2766 break;
2767 default:
2768 spv::MissingFunctionality("constant vector type");
2769 break;
2770 }
2771 ++nextConst;
2772 }
2773 } else {
2774 // we have a non-aggregate (scalar) constant
2775 bool zero = nextConst >= consts.size();
2776 spv::Id scalar = 0;
2777 switch (glslangType.getBasicType()) {
2778 case glslang::EbtInt:
2779 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst());
2780 break;
2781 case glslang::EbtUint:
2782 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst());
2783 break;
2784 case glslang::EbtFloat:
2785 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst());
2786 break;
2787 case glslang::EbtDouble:
2788 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst());
2789 break;
2790 case glslang::EbtBool:
2791 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst());
2792 break;
2793 default:
2794 spv::MissingFunctionality("constant scalar type");
2795 break;
2796 }
2797 ++nextConst;
2798 return scalar;
2799 }
2800
2801 return builder.makeCompositeConstant(typeId, spvConsts);
2802}
2803
2804}; // end anonymous namespace
2805
2806namespace glslang {
2807
John Kessenich68d78fd2015-07-12 19:28:10 -06002808void GetSpirvVersion(std::string& version)
2809{
John Kessenich9e55f632015-07-15 10:03:39 -06002810 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06002811 char buf[bufSize];
John Kessenich9e55f632015-07-15 10:03:39 -06002812 snprintf(buf, bufSize, "%d, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06002813 version = buf;
2814}
2815
John Kessenich140f3df2015-06-26 16:58:36 -06002816// Write SPIR-V out to a binary file
2817void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
2818{
2819 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06002820 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06002821 for (int i = 0; i < (int)spirv.size(); ++i) {
2822 unsigned int word = spirv[i];
2823 out.write((const char*)&word, 4);
2824 }
2825 out.close();
2826}
2827
2828//
2829// Set up the glslang traversal
2830//
2831void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
2832{
2833 TIntermNode* root = intermediate.getTreeRoot();
2834
2835 if (root == 0)
2836 return;
2837
2838 glslang::GetThreadPoolAllocator().push();
2839
2840 TGlslangToSpvTraverser it(&intermediate);
2841
2842 root->traverse(&it);
2843
2844 it.dumpSpv(spirv);
2845
2846 glslang::GetThreadPoolAllocator().pop();
2847}
2848
2849}; // end namespace glslang