blob: 5fa1a9b7f7229a9bea77f6cfcc1fabf65985f6aa [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
2//Copyright (C) 2014 LunarG, Inc.
3//
4//All rights reserved.
5//
6//Redistribution and use in source and binary forms, with or without
7//modification, are permitted provided that the following conditions
8//are met:
9//
10// Redistributions of source code must retain the above copyright
11// notice, this list of conditions and the following disclaimer.
12//
13// Redistributions in binary form must reproduce the above
14// copyright notice, this list of conditions and the following
15// disclaimer in the documentation and/or other materials provided
16// with the distribution.
17//
18// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
19// contributors may be used to endorse or promote products derived
20// from this software without specific prior written permission.
21//
22//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
32//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33//POSSIBILITY OF SUCH DAMAGE.
34
35//
36// Author: John Kessenich, LunarG
37//
38// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
46 #include "GLSL.std.450.h"
47}
John Kessenich140f3df2015-06-26 16:58:36 -060048
49// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020050#include "../glslang/MachineIndependent/localintermediate.h"
51#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060052#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060053
54#include <string>
55#include <map>
56#include <list>
57#include <vector>
58#include <stack>
59#include <fstream>
60
61namespace {
62
63const int GlslangMagic = 0x51a;
64
65//
66// The main holder of information for translating glslang to SPIR-V.
67//
68// Derives from the AST walking base class.
69//
70class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
71public:
72 TGlslangToSpvTraverser(const glslang::TIntermediate*);
73 virtual ~TGlslangToSpvTraverser();
74
75 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
76 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
77 void visitConstantUnion(glslang::TIntermConstantUnion*);
78 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
79 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
80 void visitSymbol(glslang::TIntermSymbol* symbol);
81 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
82 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
83 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
84
85 void dumpSpv(std::vector<unsigned int>& out) { builder.dump(out); }
86
87protected:
88 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
89 spv::Id getSampledType(const glslang::TSampler&);
90 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenich5e4b1242015-08-06 22:53:06 -060091 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset);
John Kessenich140f3df2015-06-26 16:58:36 -060092
93 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
94 void makeFunctions(const glslang::TIntermSequence&);
95 void makeGlobalInitializers(const glslang::TIntermSequence&);
96 void visitFunctions(const glslang::TIntermSequence&);
97 void handleFunctionEntry(const glslang::TIntermAggregate* node);
98 void translateArguments(const glslang::TIntermSequence& glslangArguments, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -060099 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
100 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600101 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
102
103 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
104 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, bool isFloat);
105 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
106 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich426394d2015-07-23 10:22:48 -0600107 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600108 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 -0600109 spv::Id createNoArgOperation(glslang::TOperator op);
110 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
111 void addDecoration(spv::Id id, spv::Decoration dec);
112 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
113 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst);
114
115 spv::Function* shaderEntry;
116 int sequenceDepth;
117
118 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
119 spv::Builder builder;
120 bool inMain;
121 bool mainTerminated;
122 bool linkageOnly;
123 const glslang::TIntermediate* glslangIntermediate;
124 spv::Id stdBuiltins;
125
John Kessenich2f273362015-07-18 22:34:27 -0600126 std::unordered_map<int, spv::Id> symbolValues;
127 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
128 std::unordered_map<std::string, spv::Function*> functionMap;
129 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap;
130 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 -0600131 std::stack<bool> breakForLoop; // false means break for switch
132 std::stack<glslang::TIntermTyped*> loopTerminal; // code from the last part of a for loop: for(...; ...; terminal), needed for e.g., continue };
133};
134
135//
136// Helper functions for translating glslang representations to SPIR-V enumerants.
137//
138
139// Translate glslang profile to SPIR-V source language.
140spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
141{
142 switch (profile) {
143 case ENoProfile:
144 case ECoreProfile:
145 case ECompatibilityProfile:
146 return spv::SourceLanguageGLSL;
147 case EEsProfile:
148 return spv::SourceLanguageESSL;
149 default:
150 return spv::SourceLanguageUnknown;
151 }
152}
153
154// Translate glslang language (stage) to SPIR-V execution model.
155spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
156{
157 switch (stage) {
158 case EShLangVertex: return spv::ExecutionModelVertex;
159 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
160 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
161 case EShLangGeometry: return spv::ExecutionModelGeometry;
162 case EShLangFragment: return spv::ExecutionModelFragment;
163 case EShLangCompute: return spv::ExecutionModelGLCompute;
164 default:
165 spv::MissingFunctionality("GLSL stage");
166 return spv::ExecutionModelFragment;
167 }
168}
169
170// Translate glslang type to SPIR-V storage class.
171spv::StorageClass TranslateStorageClass(const glslang::TType& type)
172{
173 if (type.getQualifier().isPipeInput())
174 return spv::StorageClassInput;
175 else if (type.getQualifier().isPipeOutput())
176 return spv::StorageClassOutput;
177 else if (type.getQualifier().isUniformOrBuffer()) {
178 if (type.getBasicType() == glslang::EbtBlock)
179 return spv::StorageClassUniform;
180 else
181 return spv::StorageClassUniformConstant;
182 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
183 } else {
184 switch (type.getQualifier().storage) {
185 case glslang::EvqShared: return spv::StorageClassWorkgroupLocal; break;
186 case glslang::EvqGlobal: return spv::StorageClassPrivateGlobal;
187 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
188 case glslang::EvqTemporary: return spv::StorageClassFunction;
189 default:
190 spv::MissingFunctionality("unknown glslang storage class");
191 return spv::StorageClassFunction;
192 }
193 }
194}
195
196// Translate glslang sampler type to SPIR-V dimensionality.
197spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
198{
199 switch (sampler.dim) {
200 case glslang::Esd1D: return spv::Dim1D;
201 case glslang::Esd2D: return spv::Dim2D;
202 case glslang::Esd3D: return spv::Dim3D;
203 case glslang::EsdCube: return spv::DimCube;
204 case glslang::EsdRect: return spv::DimRect;
205 case glslang::EsdBuffer: return spv::DimBuffer;
206 default:
207 spv::MissingFunctionality("unknown sampler dimension");
208 return spv::Dim2D;
209 }
210}
211
212// Translate glslang type to SPIR-V precision decorations.
213spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
214{
215 switch (type.getQualifier().precision) {
John Kessenich5e4b1242015-08-06 22:53:06 -0600216 case glslang::EpqLow: return spv::DecorationRelaxedPrecision; // TODO: Map instead to 16-bit types?
217 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
218 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600219 default:
220 return spv::NoPrecision;
221 }
222}
223
224// Translate glslang type to SPIR-V block decorations.
225spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
226{
227 if (type.getBasicType() == glslang::EbtBlock) {
228 switch (type.getQualifier().storage) {
229 case glslang::EvqUniform: return spv::DecorationBlock;
230 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
231 case glslang::EvqVaryingIn: return spv::DecorationBlock;
232 case glslang::EvqVaryingOut: return spv::DecorationBlock;
233 default:
234 spv::MissingFunctionality("kind of block");
235 break;
236 }
237 }
238
239 return (spv::Decoration)spv::BadValue;
240}
241
242// Translate glslang type to SPIR-V layout decorations.
243spv::Decoration TranslateLayoutDecoration(const glslang::TType& type)
244{
245 if (type.isMatrix()) {
246 switch (type.getQualifier().layoutMatrix) {
247 case glslang::ElmRowMajor:
248 return spv::DecorationRowMajor;
249 default:
250 return spv::DecorationColMajor;
251 }
252 } else {
253 switch (type.getBasicType()) {
254 default:
255 return (spv::Decoration)spv::BadValue;
256 break;
257 case glslang::EbtBlock:
258 switch (type.getQualifier().storage) {
259 case glslang::EvqUniform:
260 case glslang::EvqBuffer:
261 switch (type.getQualifier().layoutPacking) {
262 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600263 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
264 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600265 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600266 }
267 case glslang::EvqVaryingIn:
268 case glslang::EvqVaryingOut:
269 if (type.getQualifier().layoutPacking != glslang::ElpNone)
270 spv::MissingFunctionality("in/out block layout");
271 return (spv::Decoration)spv::BadValue;
272 default:
273 spv::MissingFunctionality("block storage qualification");
274 return (spv::Decoration)spv::BadValue;
275 }
276 }
277 }
278}
279
280// Translate glslang type to SPIR-V interpolation decorations.
281spv::Decoration TranslateInterpolationDecoration(const glslang::TType& type)
282{
283 if (type.getQualifier().smooth)
284 return spv::DecorationSmooth;
285 if (type.getQualifier().nopersp)
286 return spv::DecorationNoperspective;
287 else if (type.getQualifier().patch)
288 return spv::DecorationPatch;
289 else if (type.getQualifier().flat)
290 return spv::DecorationFlat;
291 else if (type.getQualifier().centroid)
292 return spv::DecorationCentroid;
293 else if (type.getQualifier().sample)
294 return spv::DecorationSample;
295 else
296 return (spv::Decoration)spv::BadValue;
297}
298
299// If glslang type is invaraiant, return SPIR-V invariant decoration.
300spv::Decoration TranslateInvariantDecoration(const glslang::TType& type)
301{
302 if (type.getQualifier().invariant)
303 return spv::DecorationInvariant;
304 else
305 return (spv::Decoration)spv::BadValue;
306}
307
308// Translate glslang built-in variable to SPIR-V built in decoration.
309spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
310{
311 switch (builtIn) {
312 case glslang::EbvPosition: return spv::BuiltInPosition;
313 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600314 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
315 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
316 case glslang::EbvVertexId: return spv::BuiltInVertexId;
317 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
318 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
319 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
320 case glslang::EbvLayer: return spv::BuiltInLayer;
321 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
322 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
323 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
324 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
325 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
326 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
327 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
328 case glslang::EbvFace: return spv::BuiltInFrontFacing;
329 case glslang::EbvSampleId: return spv::BuiltInSampleId;
330 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
331 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
332 case glslang::EbvFragColor: return spv::BuiltInFragColor;
333 case glslang::EbvFragData: return spv::BuiltInFragColor;
334 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
335 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
336 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
337 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
338 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
339 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
340 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
341 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
342 default: return (spv::BuiltIn)spv::BadValue;
343 }
344}
345
346//
347// Implement the TGlslangToSpvTraverser class.
348//
349
350TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
351 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
352 builder(GlslangMagic),
353 inMain(false), mainTerminated(false), linkageOnly(false),
354 glslangIntermediate(glslangIntermediate)
355{
356 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
357
358 builder.clearAccessChain();
359 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
360 stdBuiltins = builder.import("GLSL.std.450");
361 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
362 shaderEntry = builder.makeMain();
John Kessenich5e4b1242015-08-06 22:53:06 -0600363 builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600364
365 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600366 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
367 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600368 builder.addSourceExtension(it->c_str());
369
370 // Add the top-level modes for this shader.
371
372 if (glslangIntermediate->getXfbMode())
373 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
374
375 unsigned int mode;
376 switch (glslangIntermediate->getStage()) {
377 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600378 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600379 break;
380
381 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600382 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600383 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
384 break;
385
386 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600387 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600388 switch (glslangIntermediate->getInputPrimitive()) {
389 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
390 case glslang::ElgQuads: mode = spv::ExecutionModeInputQuads; break;
391 case glslang::ElgIsolines: mode = spv::ExecutionModeInputIsolines; break;
392 default: mode = spv::BadValue; break;
393 }
394 if (mode != spv::BadValue)
395 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
396
397 // TODO
398 //builder.addExecutionMode(spv::VertexSpacingMdName, glslangIntermediate->getVertexSpacing());
399 //builder.addExecutionMode(spv::VertexOrderMdName, glslangIntermediate->getVertexOrder());
400 //builder.addExecutionMode(spv::PointModeMdName, glslangIntermediate->getPointMode());
401 break;
402
403 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600404 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600405 switch (glslangIntermediate->getInputPrimitive()) {
406 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
407 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
408 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
409 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
410 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
411 default: mode = spv::BadValue; break;
412 }
413 if (mode != spv::BadValue)
414 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
415 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
416
417 switch (glslangIntermediate->getOutputPrimitive()) {
418 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
419 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
420 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
421 default: mode = spv::BadValue; break;
422 }
423 if (mode != spv::BadValue)
424 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
425 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
426 break;
427
428 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600429 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600430 if (glslangIntermediate->getPixelCenterInteger())
431 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
432 if (glslangIntermediate->getOriginUpperLeft())
433 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600434 else
435 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kessenich140f3df2015-06-26 16:58:36 -0600436 break;
437
438 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600439 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600440 break;
441
442 default:
443 break;
444 }
445
446}
447
448TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
449{
450 if (! mainTerminated) {
451 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
452 builder.setBuildPoint(lastMainBlock);
453 builder.leaveFunction(true);
454 }
455}
456
457//
458// Implement the traversal functions.
459//
460// Return true from interior nodes to have the external traversal
461// continue on to children. Return false if children were
462// already processed.
463//
464
465//
466// Symbols can turn into
467// - uniform/input reads
468// - output writes
469// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
470// - something simple that degenerates into the last bullet
471//
472void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
473{
474 // getSymbolId() will set up all the IO decorations on the first call.
475 // Formal function parameters were mapped during makeFunctions().
476 spv::Id id = getSymbolId(symbol);
477
478 if (! linkageOnly) {
479 // Prepare to generate code for the access
480
481 // L-value chains will be computed left to right. We're on the symbol now,
482 // which is the left-most part of the access chain, so now is "clear" time,
483 // followed by setting the base.
484 builder.clearAccessChain();
485
486 // For now, we consider all user variables as being in memory, so they are pointers,
487 // except for "const in" arguments to a function, which are an intermediate object.
488 // See comments in handleUserFunctionCall().
489 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
490 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
491 builder.setAccessChainRValue(id);
492 else
493 builder.setAccessChainLValue(id);
494 }
495}
496
497bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
498{
499 // First, handle special cases
500 switch (node->getOp()) {
501 case glslang::EOpAssign:
502 case glslang::EOpAddAssign:
503 case glslang::EOpSubAssign:
504 case glslang::EOpMulAssign:
505 case glslang::EOpVectorTimesMatrixAssign:
506 case glslang::EOpVectorTimesScalarAssign:
507 case glslang::EOpMatrixTimesScalarAssign:
508 case glslang::EOpMatrixTimesMatrixAssign:
509 case glslang::EOpDivAssign:
510 case glslang::EOpModAssign:
511 case glslang::EOpAndAssign:
512 case glslang::EOpInclusiveOrAssign:
513 case glslang::EOpExclusiveOrAssign:
514 case glslang::EOpLeftShiftAssign:
515 case glslang::EOpRightShiftAssign:
516 // A bin-op assign "a += b" means the same thing as "a = a + b"
517 // where a is evaluated before b. For a simple assignment, GLSL
518 // says to evaluate the left before the right. So, always, left
519 // node then right node.
520 {
521 // get the left l-value, save it away
522 builder.clearAccessChain();
523 node->getLeft()->traverse(this);
524 spv::Builder::AccessChain lValue = builder.getAccessChain();
525
526 // evaluate the right
527 builder.clearAccessChain();
528 node->getRight()->traverse(this);
529 spv::Id rValue = builder.accessChainLoad(TranslatePrecisionDecoration(node->getRight()->getType()));
530
531 if (node->getOp() != glslang::EOpAssign) {
532 // the left is also an r-value
533 builder.setAccessChain(lValue);
534 spv::Id leftRValue = builder.accessChainLoad(TranslatePrecisionDecoration(node->getLeft()->getType()));
535
536 // do the operation
537 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
538 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
539 node->getType().getBasicType());
540
541 // these all need their counterparts in createBinaryOperation()
542 if (rValue == 0)
543 spv::MissingFunctionality("createBinaryOperation");
544 }
545
546 // store the result
547 builder.setAccessChain(lValue);
548 builder.accessChainStore(rValue);
549
550 // assignments are expressions having an rValue after they are evaluated...
551 builder.clearAccessChain();
552 builder.setAccessChainRValue(rValue);
553 }
554 return false;
555 case glslang::EOpIndexDirect:
556 case glslang::EOpIndexDirectStruct:
557 {
558 // Get the left part of the access chain.
559 node->getLeft()->traverse(this);
560
561 // Add the next element in the chain
562
563 int index = 0;
564 if (node->getRight()->getAsConstantUnion() == 0)
565 spv::MissingFunctionality("direct index without a constant node");
566 else
567 index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
568
569 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
570 // This may be, e.g., an anonymous block-member selection, which generally need
571 // index remapping due to hidden members in anonymous blocks.
572 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
573 if (remapper.size() == 0)
574 spv::MissingFunctionality("block without member remapping");
575 else
576 index = remapper[index];
577 }
578
579 if (! node->getLeft()->getType().isArray() &&
580 node->getLeft()->getType().isVector() &&
581 node->getOp() == glslang::EOpIndexDirect) {
582 // This is essentially a hard-coded vector swizzle of size 1,
583 // so short circuit the access-chain stuff with a swizzle.
584 std::vector<unsigned> swizzle;
585 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
586 builder.accessChainPushSwizzle(swizzle);
587 } else {
588 // normal case for indexing array or structure or block
589 builder.accessChainPush(builder.makeIntConstant(index), convertGlslangToSpvType(node->getType()));
590 }
591 }
592 return false;
593 case glslang::EOpIndexIndirect:
594 {
595 // Structure or array or vector indirection.
596 // Will use native SPIR-V access-chain for struct and array indirection;
597 // matrices are arrays of vectors, so will also work for a matrix.
598 // Will use the access chain's 'component' for variable index into a vector.
599
600 // This adapter is building access chains left to right.
601 // Set up the access chain to the left.
602 node->getLeft()->traverse(this);
603
604 // save it so that computing the right side doesn't trash it
605 spv::Builder::AccessChain partial = builder.getAccessChain();
606
607 // compute the next index in the chain
608 builder.clearAccessChain();
609 node->getRight()->traverse(this);
610 spv::Id index = builder.accessChainLoad(TranslatePrecisionDecoration(node->getRight()->getType()));
611
612 // restore the saved access chain
613 builder.setAccessChain(partial);
614
615 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
616 builder.accessChainPushComponent(index);
617 else
618 builder.accessChainPush(index, convertGlslangToSpvType(node->getType()));
619 }
620 return false;
621 case glslang::EOpVectorSwizzle:
622 {
623 node->getLeft()->traverse(this);
624 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
625 std::vector<unsigned> swizzle;
626 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
627 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
628 builder.accessChainPushSwizzle(swizzle);
629 }
630 return false;
631 default:
632 break;
633 }
634
635 // Assume generic binary op...
636
637 // Get the operands
638 builder.clearAccessChain();
639 node->getLeft()->traverse(this);
640 spv::Id left = builder.accessChainLoad(TranslatePrecisionDecoration(node->getLeft()->getType()));
641
642 builder.clearAccessChain();
643 node->getRight()->traverse(this);
644 spv::Id right = builder.accessChainLoad(TranslatePrecisionDecoration(node->getRight()->getType()));
645
646 spv::Id result;
647 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
648
649 result = createBinaryOperation(node->getOp(), precision,
650 convertGlslangToSpvType(node->getType()), left, right,
651 node->getLeft()->getType().getBasicType());
652
653 if (! result) {
654 spv::MissingFunctionality("glslang binary operation");
655 } else {
656 builder.clearAccessChain();
657 builder.setAccessChainRValue(result);
658
659 return false;
660 }
661
662 return true;
663}
664
665bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
666{
John Kessenichfc51d282015-08-19 13:34:18 -0600667 spv::Id result = spv::NoResult;
668
669 // try texturing first
670 result = createImageTextureFunctionCall(node);
671 if (result != spv::NoResult) {
672 builder.clearAccessChain();
673 builder.setAccessChainRValue(result);
674
675 return false; // done with this node
676 }
677
678 // Non-texturing.
679 // Start by evaluating the operand
680
John Kessenich140f3df2015-06-26 16:58:36 -0600681 builder.clearAccessChain();
682 node->getOperand()->traverse(this);
683 spv::Id operand = builder.accessChainLoad(TranslatePrecisionDecoration(node->getOperand()->getType()));
684
685 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
686
687 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600688 if (! result)
689 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600690
691 // if not, then possibly an operation
692 if (! result)
John Kessenichfc51d282015-08-19 13:34:18 -0600693 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand,
694 node->getBasicType() == glslang::EbtFloat || node->getBasicType() == glslang::EbtDouble);
John Kessenich140f3df2015-06-26 16:58:36 -0600695
696 if (result) {
697 builder.clearAccessChain();
698 builder.setAccessChainRValue(result);
699
700 return false; // done with this node
701 }
702
703 // it must be a special case, check...
704 switch (node->getOp()) {
705 case glslang::EOpPostIncrement:
706 case glslang::EOpPostDecrement:
707 case glslang::EOpPreIncrement:
708 case glslang::EOpPreDecrement:
709 {
710 // we need the integer value "1" or the floating point "1.0" to add/subtract
711 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
712 builder.makeFloatConstant(1.0F) :
713 builder.makeIntConstant(1);
714 glslang::TOperator op;
715 if (node->getOp() == glslang::EOpPreIncrement ||
716 node->getOp() == glslang::EOpPostIncrement)
717 op = glslang::EOpAdd;
718 else
719 op = glslang::EOpSub;
720
721 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
722 convertGlslangToSpvType(node->getType()), operand, one,
723 node->getType().getBasicType());
724 if (result == 0)
725 spv::MissingFunctionality("createBinaryOperation for unary");
726
727 // The result of operation is always stored, but conditionally the
728 // consumed result. The consumed result is always an r-value.
729 builder.accessChainStore(result);
730 builder.clearAccessChain();
731 if (node->getOp() == glslang::EOpPreIncrement ||
732 node->getOp() == glslang::EOpPreDecrement)
733 builder.setAccessChainRValue(result);
734 else
735 builder.setAccessChainRValue(operand);
736 }
737
738 return false;
739
740 case glslang::EOpEmitStreamVertex:
741 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
742 return false;
743 case glslang::EOpEndStreamPrimitive:
744 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
745 return false;
746
747 default:
748 spv::MissingFunctionality("glslang unary");
749 break;
750 }
751
752 return true;
753}
754
755bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
756{
John Kessenichfc51d282015-08-19 13:34:18 -0600757 spv::Id result = spv::NoResult;
758
759 // try texturing
760 result = createImageTextureFunctionCall(node);
761 if (result != spv::NoResult) {
762 builder.clearAccessChain();
763 builder.setAccessChainRValue(result);
764
765 return false;
766 }
767
John Kessenich140f3df2015-06-26 16:58:36 -0600768 glslang::TOperator binOp = glslang::EOpNull;
769 bool reduceComparison = true;
770 bool isMatrix = false;
771 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600772 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600773
774 assert(node->getOp());
775
776 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
777
778 switch (node->getOp()) {
779 case glslang::EOpSequence:
780 {
781 if (preVisit)
782 ++sequenceDepth;
783 else
784 --sequenceDepth;
785
786 if (sequenceDepth == 1) {
787 // If this is the parent node of all the functions, we want to see them
788 // early, so all call points have actual SPIR-V functions to reference.
789 // In all cases, still let the traverser visit the children for us.
790 makeFunctions(node->getAsAggregate()->getSequence());
791
792 // Also, we want all globals initializers to go into the entry of main(), before
793 // anything else gets there, so visit out of order, doing them all now.
794 makeGlobalInitializers(node->getAsAggregate()->getSequence());
795
796 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
797 // so do them manually.
798 visitFunctions(node->getAsAggregate()->getSequence());
799
800 return false;
801 }
802
803 return true;
804 }
805 case glslang::EOpLinkerObjects:
806 {
807 if (visit == glslang::EvPreVisit)
808 linkageOnly = true;
809 else
810 linkageOnly = false;
811
812 return true;
813 }
814 case glslang::EOpComma:
815 {
816 // processing from left to right naturally leaves the right-most
817 // lying around in the access chain
818 glslang::TIntermSequence& glslangOperands = node->getSequence();
819 for (int i = 0; i < (int)glslangOperands.size(); ++i)
820 glslangOperands[i]->traverse(this);
821
822 return false;
823 }
824 case glslang::EOpFunction:
825 if (visit == glslang::EvPreVisit) {
826 if (isShaderEntrypoint(node)) {
827 inMain = true;
828 builder.setBuildPoint(shaderEntry->getLastBlock());
829 } else {
830 handleFunctionEntry(node);
831 }
832 } else {
833 if (inMain)
834 mainTerminated = true;
835 builder.leaveFunction(inMain);
836 inMain = false;
837 }
838
839 return true;
840 case glslang::EOpParameters:
841 // Parameters will have been consumed by EOpFunction processing, but not
842 // the body, so we still visited the function node's children, making this
843 // child redundant.
844 return false;
845 case glslang::EOpFunctionCall:
846 {
847 if (node->isUserDefined())
848 result = handleUserFunctionCall(node);
John Kessenich140f3df2015-06-26 16:58:36 -0600849
850 if (! result) {
851 spv::MissingFunctionality("glslang function call");
852 glslang::TConstUnionArray emptyConsts;
853 int nextConst = 0;
854 result = createSpvConstant(node->getType(), emptyConsts, nextConst);
855 }
856 builder.clearAccessChain();
857 builder.setAccessChainRValue(result);
858
859 return false;
860 }
861 case glslang::EOpConstructMat2x2:
862 case glslang::EOpConstructMat2x3:
863 case glslang::EOpConstructMat2x4:
864 case glslang::EOpConstructMat3x2:
865 case glslang::EOpConstructMat3x3:
866 case glslang::EOpConstructMat3x4:
867 case glslang::EOpConstructMat4x2:
868 case glslang::EOpConstructMat4x3:
869 case glslang::EOpConstructMat4x4:
870 case glslang::EOpConstructDMat2x2:
871 case glslang::EOpConstructDMat2x3:
872 case glslang::EOpConstructDMat2x4:
873 case glslang::EOpConstructDMat3x2:
874 case glslang::EOpConstructDMat3x3:
875 case glslang::EOpConstructDMat3x4:
876 case glslang::EOpConstructDMat4x2:
877 case glslang::EOpConstructDMat4x3:
878 case glslang::EOpConstructDMat4x4:
879 isMatrix = true;
880 // fall through
881 case glslang::EOpConstructFloat:
882 case glslang::EOpConstructVec2:
883 case glslang::EOpConstructVec3:
884 case glslang::EOpConstructVec4:
885 case glslang::EOpConstructDouble:
886 case glslang::EOpConstructDVec2:
887 case glslang::EOpConstructDVec3:
888 case glslang::EOpConstructDVec4:
889 case glslang::EOpConstructBool:
890 case glslang::EOpConstructBVec2:
891 case glslang::EOpConstructBVec3:
892 case glslang::EOpConstructBVec4:
893 case glslang::EOpConstructInt:
894 case glslang::EOpConstructIVec2:
895 case glslang::EOpConstructIVec3:
896 case glslang::EOpConstructIVec4:
897 case glslang::EOpConstructUint:
898 case glslang::EOpConstructUVec2:
899 case glslang::EOpConstructUVec3:
900 case glslang::EOpConstructUVec4:
901 case glslang::EOpConstructStruct:
902 {
903 std::vector<spv::Id> arguments;
904 translateArguments(node->getSequence(), arguments);
905 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
906 spv::Id constructed;
907 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
908 std::vector<spv::Id> constituents;
909 for (int c = 0; c < (int)arguments.size(); ++c)
910 constituents.push_back(arguments[c]);
911 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
912 } else {
913 if (isMatrix)
914 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
915 else
916 constructed = builder.createConstructor(precision, arguments, resultTypeId);
917 }
918
919 builder.clearAccessChain();
920 builder.setAccessChainRValue(constructed);
921
922 return false;
923 }
924
925 // These six are component-wise compares with component-wise results.
926 // Forward on to createBinaryOperation(), requesting a vector result.
927 case glslang::EOpLessThan:
928 case glslang::EOpGreaterThan:
929 case glslang::EOpLessThanEqual:
930 case glslang::EOpGreaterThanEqual:
931 case glslang::EOpVectorEqual:
932 case glslang::EOpVectorNotEqual:
933 {
934 // Map the operation to a binary
935 binOp = node->getOp();
936 reduceComparison = false;
937 switch (node->getOp()) {
938 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
939 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
940 default: binOp = node->getOp(); break;
941 }
942
943 break;
944 }
945 case glslang::EOpMul:
946 // compontent-wise matrix multiply
947 binOp = glslang::EOpMul;
948 break;
949 case glslang::EOpOuterProduct:
950 // two vectors multiplied to make a matrix
951 binOp = glslang::EOpOuterProduct;
952 break;
953 case glslang::EOpDot:
954 {
955 // for scalar dot product, use multiply
956 glslang::TIntermSequence& glslangOperands = node->getSequence();
957 if (! glslangOperands[0]->getAsTyped()->isVector())
958 binOp = glslang::EOpMul;
959 break;
960 }
961 case glslang::EOpMod:
962 // when an aggregate, this is the floating-point mod built-in function,
963 // which can be emitted by the one in createBinaryOperation()
964 binOp = glslang::EOpMod;
965 break;
966 case glslang::EOpArrayLength:
967 {
968 glslang::TIntermTyped* typedNode = node->getSequence()[0]->getAsTyped();
969 assert(typedNode);
John Kessenich65c78a02015-08-10 17:08:55 -0600970 spv::Id length = builder.makeIntConstant(typedNode->getType().getOuterArraySize());
John Kessenich140f3df2015-06-26 16:58:36 -0600971
972 builder.clearAccessChain();
973 builder.setAccessChainRValue(length);
974
975 return false;
976 }
977 case glslang::EOpEmitVertex:
978 case glslang::EOpEndPrimitive:
979 case glslang::EOpBarrier:
980 case glslang::EOpMemoryBarrier:
981 case glslang::EOpMemoryBarrierAtomicCounter:
982 case glslang::EOpMemoryBarrierBuffer:
983 case glslang::EOpMemoryBarrierImage:
984 case glslang::EOpMemoryBarrierShared:
985 case glslang::EOpGroupMemoryBarrier:
986 noReturnValue = true;
987 // These all have 0 operands and will naturally finish up in the code below for 0 operands
988 break;
989
John Kessenich426394d2015-07-23 10:22:48 -0600990 case glslang::EOpAtomicAdd:
991 case glslang::EOpAtomicMin:
992 case glslang::EOpAtomicMax:
993 case glslang::EOpAtomicAnd:
994 case glslang::EOpAtomicOr:
995 case glslang::EOpAtomicXor:
996 case glslang::EOpAtomicExchange:
997 case glslang::EOpAtomicCompSwap:
998 atomic = true;
999 break;
1000
John Kessenichfc51d282015-08-19 13:34:18 -06001001 case glslang::EOpAddCarry:
1002 case glslang::EOpSubBorrow:
1003 case glslang::EOpUMulExtended:
1004 case glslang::EOpIMulExtended:
1005 case glslang::EOpBitfieldExtract:
1006 case glslang::EOpBitfieldInsert:
1007 spv::MissingFunctionality("integer aggregate");
1008 break;
1009
1010 case glslang::EOpFma:
John Kessenich78258d32015-08-19 17:30:12 -06001011 case glslang::EOpFrexp:
1012 case glslang::EOpLdexp:
John Kessenichfc51d282015-08-19 13:34:18 -06001013 spv::MissingFunctionality("fma/frexp/ldexp aggregate");
1014 break;
1015
John Kessenich140f3df2015-06-26 16:58:36 -06001016 default:
1017 break;
1018 }
1019
1020 //
1021 // See if it maps to a regular operation.
1022 //
John Kessenich140f3df2015-06-26 16:58:36 -06001023 if (binOp != glslang::EOpNull) {
1024 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1025 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1026 assert(left && right);
1027
1028 builder.clearAccessChain();
1029 left->traverse(this);
1030 spv::Id leftId = builder.accessChainLoad(TranslatePrecisionDecoration(left->getType()));
1031
1032 builder.clearAccessChain();
1033 right->traverse(this);
1034 spv::Id rightId = builder.accessChainLoad(TranslatePrecisionDecoration(right->getType()));
1035
1036 result = createBinaryOperation(binOp, precision,
1037 convertGlslangToSpvType(node->getType()), leftId, rightId,
1038 left->getType().getBasicType(), reduceComparison);
1039
1040 // code above should only make binOp that exists in createBinaryOperation
1041 if (result == 0)
1042 spv::MissingFunctionality("createBinaryOperation for aggregate");
1043
1044 builder.clearAccessChain();
1045 builder.setAccessChainRValue(result);
1046
1047 return false;
1048 }
1049
John Kessenich426394d2015-07-23 10:22:48 -06001050 //
1051 // Create the list of operands.
1052 //
John Kessenich140f3df2015-06-26 16:58:36 -06001053 glslang::TIntermSequence& glslangOperands = node->getSequence();
1054 std::vector<spv::Id> operands;
1055 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1056 builder.clearAccessChain();
1057 glslangOperands[arg]->traverse(this);
1058
1059 // special case l-value operands; there are just a few
1060 bool lvalue = false;
1061 switch (node->getOp()) {
1062 //case glslang::EOpFrexp:
1063 case glslang::EOpModf:
1064 if (arg == 1)
1065 lvalue = true;
1066 break;
1067 //case glslang::EOpUAddCarry:
1068 //case glslang::EOpUSubBorrow:
1069 //case glslang::EOpUMulExtended:
1070 default:
1071 break;
1072 }
1073 if (lvalue)
1074 operands.push_back(builder.accessChainGetLValue());
1075 else
1076 operands.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangOperands[arg]->getAsTyped()->getType())));
1077 }
John Kessenich426394d2015-07-23 10:22:48 -06001078
1079 if (atomic) {
1080 // Handle all atomics
1081 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands);
1082 } else {
1083 // Pass through to generic operations.
1084 switch (glslangOperands.size()) {
1085 case 0:
1086 result = createNoArgOperation(node->getOp());
1087 break;
1088 case 1:
1089 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), node->getType().getBasicType() == glslang::EbtFloat || node->getType().getBasicType() == glslang::EbtDouble);
1090 break;
1091 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001092 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001093 break;
1094 }
John Kessenich140f3df2015-06-26 16:58:36 -06001095 }
1096
1097 if (noReturnValue)
1098 return false;
1099
1100 if (! result) {
1101 spv::MissingFunctionality("glslang aggregate");
1102 return true;
1103 } else {
1104 builder.clearAccessChain();
1105 builder.setAccessChainRValue(result);
1106 return false;
1107 }
1108}
1109
1110bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1111{
1112 // This path handles both if-then-else and ?:
1113 // The if-then-else has a node type of void, while
1114 // ?: has a non-void node type
1115 spv::Id result = 0;
1116 if (node->getBasicType() != glslang::EbtVoid) {
1117 // don't handle this as just on-the-fly temporaries, because there will be two names
1118 // and better to leave SSA to later passes
1119 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1120 }
1121
1122 // emit the condition before doing anything with selection
1123 node->getCondition()->traverse(this);
1124
1125 // make an "if" based on the value created by the condition
1126 spv::Builder::If ifBuilder(builder.accessChainLoad(spv::NoPrecision), builder);
1127
1128 if (node->getTrueBlock()) {
1129 // emit the "then" statement
1130 node->getTrueBlock()->traverse(this);
1131 if (result)
1132 builder.createStore(builder.accessChainLoad(TranslatePrecisionDecoration(node->getTrueBlock()->getAsTyped()->getType())), result);
1133 }
1134
1135 if (node->getFalseBlock()) {
1136 ifBuilder.makeBeginElse();
1137 // emit the "else" statement
1138 node->getFalseBlock()->traverse(this);
1139 if (result)
1140 builder.createStore(builder.accessChainLoad(TranslatePrecisionDecoration(node->getFalseBlock()->getAsTyped()->getType())), result);
1141 }
1142
1143 ifBuilder.makeEndIf();
1144
1145 if (result) {
1146 // GLSL only has r-values as the result of a :?, but
1147 // if we have an l-value, that can be more efficient if it will
1148 // become the base of a complex r-value expression, because the
1149 // next layer copies r-values into memory to use the access-chain mechanism
1150 builder.clearAccessChain();
1151 builder.setAccessChainLValue(result);
1152 }
1153
1154 return false;
1155}
1156
1157bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1158{
1159 // emit and get the condition before doing anything with switch
1160 node->getCondition()->traverse(this);
1161 spv::Id selector = builder.accessChainLoad(TranslatePrecisionDecoration(node->getCondition()->getAsTyped()->getType()));
1162
1163 // browse the children to sort out code segments
1164 int defaultSegment = -1;
1165 std::vector<TIntermNode*> codeSegments;
1166 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1167 std::vector<int> caseValues;
1168 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1169 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1170 TIntermNode* child = *c;
1171 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001172 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001173 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001174 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001175 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1176 } else
1177 codeSegments.push_back(child);
1178 }
1179
1180 // handle the case where the last code segment is missing, due to no code
1181 // statements between the last case and the end of the switch statement
1182 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1183 (int)codeSegments.size() == defaultSegment)
1184 codeSegments.push_back(nullptr);
1185
1186 // make the switch statement
1187 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001188 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001189
1190 // emit all the code in the segments
1191 breakForLoop.push(false);
1192 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1193 builder.nextSwitchSegment(segmentBlocks, s);
1194 if (codeSegments[s])
1195 codeSegments[s]->traverse(this);
1196 else
1197 builder.addSwitchBreak();
1198 }
1199 breakForLoop.pop();
1200
1201 builder.endSwitch(segmentBlocks);
1202
1203 return false;
1204}
1205
1206void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1207{
1208 int nextConst = 0;
1209 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1210
1211 builder.clearAccessChain();
1212 builder.setAccessChainRValue(constant);
1213}
1214
1215bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1216{
1217 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1218 loopTerminal.push(node->getTerminal());
1219
David Netoc22f37c2015-07-15 16:21:26 -04001220 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001221
1222 if (node->getTest()) {
1223 node->getTest()->traverse(this);
1224 // the AST only contained the test computation, not the branch, we have to add it
1225 spv::Id condition = builder.accessChainLoad(TranslatePrecisionDecoration(node->getTest()->getType()));
1226 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001227 } else {
1228 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001229 }
1230
David Netoc22f37c2015-07-15 16:21:26 -04001231 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001232 breakForLoop.push(true);
1233 node->getBody()->traverse(this);
1234 breakForLoop.pop();
1235 }
1236
1237 if (loopTerminal.top())
1238 loopTerminal.top()->traverse(this);
1239
1240 builder.closeLoop();
1241
1242 loopTerminal.pop();
1243
1244 return false;
1245}
1246
1247bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1248{
1249 if (node->getExpression())
1250 node->getExpression()->traverse(this);
1251
1252 switch (node->getFlowOp()) {
1253 case glslang::EOpKill:
1254 builder.makeDiscard();
1255 break;
1256 case glslang::EOpBreak:
1257 if (breakForLoop.top())
1258 builder.createLoopExit();
1259 else
1260 builder.addSwitchBreak();
1261 break;
1262 case glslang::EOpContinue:
1263 if (loopTerminal.top())
1264 loopTerminal.top()->traverse(this);
1265 builder.createLoopContinue();
1266 break;
1267 case glslang::EOpReturn:
1268 if (inMain)
1269 builder.makeMainReturn();
1270 else if (node->getExpression())
1271 builder.makeReturn(false, builder.accessChainLoad(TranslatePrecisionDecoration(node->getExpression()->getType())));
1272 else
1273 builder.makeReturn();
1274
1275 builder.clearAccessChain();
1276 break;
1277
1278 default:
1279 spv::MissingFunctionality("branch type");
1280 break;
1281 }
1282
1283 return false;
1284}
1285
1286spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1287{
1288 // First, steer off constants, which are not SPIR-V variables, but
1289 // can still have a mapping to a SPIR-V Id.
1290 if (node->getQualifier().storage == glslang::EvqConst) {
1291 int nextConst = 0;
1292 return createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1293 }
1294
1295 // Now, handle actual variables
1296 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1297 spv::Id spvType = convertGlslangToSpvType(node->getType());
1298
1299 const char* name = node->getName().c_str();
1300 if (glslang::IsAnonymous(name))
1301 name = "";
1302
1303 return builder.createVariable(storageClass, spvType, name);
1304}
1305
1306// Return type Id of the sampled type.
1307spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1308{
1309 switch (sampler.type) {
1310 case glslang::EbtFloat: return builder.makeFloatType(32);
1311 case glslang::EbtInt: return builder.makeIntType(32);
1312 case glslang::EbtUint: return builder.makeUintType(32);
1313 default:
1314 spv::MissingFunctionality("sampled type");
1315 return builder.makeFloatType(32);
1316 }
1317}
1318
1319// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1320spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1321{
1322 spv::Id spvType = 0;
1323
1324 switch (type.getBasicType()) {
1325 case glslang::EbtVoid:
1326 spvType = builder.makeVoidType();
1327 if (type.isArray())
1328 spv::MissingFunctionality("array of void");
1329 break;
1330 case glslang::EbtFloat:
1331 spvType = builder.makeFloatType(32);
1332 break;
1333 case glslang::EbtDouble:
1334 spvType = builder.makeFloatType(64);
1335 break;
1336 case glslang::EbtBool:
1337 spvType = builder.makeBoolType();
1338 break;
1339 case glslang::EbtInt:
1340 spvType = builder.makeIntType(32);
1341 break;
1342 case glslang::EbtUint:
1343 spvType = builder.makeUintType(32);
1344 break;
John Kessenich426394d2015-07-23 10:22:48 -06001345 case glslang::EbtAtomicUint:
1346 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1347 spvType = builder.makeUintType(32);
1348 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001349 case glslang::EbtSampler:
1350 {
1351 const glslang::TSampler& sampler = type.getSampler();
John Kessenich5e4b1242015-08-06 22:53:06 -06001352 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1353 sampler.image ? 2 : 1, spv::ImageFormatUnknown); // TODO: translate format, needed for GLSL image ops
1354 // OpenGL "textures" need to be combined with a sampler
1355 if (! sampler.image)
1356 spvType = builder.makeSampledImageType(spvType);
John Kessenich140f3df2015-06-26 16:58:36 -06001357 }
1358 break;
1359 case glslang::EbtStruct:
1360 case glslang::EbtBlock:
1361 {
1362 // If we've seen this struct type, return it
1363 const glslang::TTypeList* glslangStruct = type.getStruct();
1364 std::vector<spv::Id> structFields;
1365 spvType = structMap[glslangStruct];
1366 if (spvType)
1367 break;
1368
1369 // else, we haven't seen it...
1370
1371 // Create a vector of struct types for SPIR-V to consume
1372 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1373 if (type.getBasicType() == glslang::EbtBlock)
1374 memberRemapper[glslangStruct].resize(glslangStruct->size());
1375 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1376 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1377 if (glslangType.hiddenMember()) {
1378 ++memberDelta;
1379 if (type.getBasicType() == glslang::EbtBlock)
1380 memberRemapper[glslangStruct][i] = -1;
1381 } else {
1382 if (type.getBasicType() == glslang::EbtBlock)
1383 memberRemapper[glslangStruct][i] = i - memberDelta;
1384 structFields.push_back(convertGlslangToSpvType(glslangType));
1385 }
1386 }
1387
1388 // Make the SPIR-V type
1389 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
1390 structMap[glslangStruct] = spvType;
1391
1392 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001393 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001394 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1395 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1396 int member = i;
1397 if (type.getBasicType() == glslang::EbtBlock)
1398 member = memberRemapper[glslangStruct][i];
1399 // using -1 above to indicate a hidden member
1400 if (member >= 0) {
1401 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
1402 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType));
1403 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1404 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1405 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1406 if (glslangType.getQualifier().hasLocation())
1407 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1408 if (glslangType.getQualifier().hasComponent())
1409 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1410 if (glslangType.getQualifier().hasXfbOffset())
1411 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001412 else {
1413 // figure out what to do with offset, which is accumulating
1414 int nextOffset;
1415 updateMemberOffset(type, glslangType, offset, nextOffset);
1416 if (offset >= 0)
1417 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutOffset);
1418 offset = nextOffset;
1419 }
John Kessenich140f3df2015-06-26 16:58:36 -06001420
1421 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001422 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1423 if (builtIn != spv::BadValue)
1424 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001425 }
1426 }
1427
1428 // Decorate the structure
1429 addDecoration(spvType, TranslateLayoutDecoration(type));
1430 addDecoration(spvType, TranslateBlockDecoration(type));
1431 if (type.getQualifier().hasStream())
1432 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1433 if (glslangIntermediate->getXfbMode()) {
1434 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001435 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001436 if (type.getQualifier().hasXfbBuffer())
1437 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1438 }
1439 }
1440 break;
1441 default:
1442 spv::MissingFunctionality("basic type");
1443 break;
1444 }
1445
1446 if (type.isMatrix())
1447 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1448 else {
1449 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1450 if (type.getVectorSize() > 1)
1451 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1452 }
1453
1454 if (type.isArray()) {
1455 unsigned arraySize;
1456 if (! type.isExplicitlySizedArray()) {
1457 spv::MissingFunctionality("Unsized array");
1458 arraySize = 8;
1459 } else
John Kessenich65c78a02015-08-10 17:08:55 -06001460 arraySize = type.getOuterArraySize();
John Kessenich140f3df2015-06-26 16:58:36 -06001461 spvType = builder.makeArrayType(spvType, arraySize);
1462 }
1463
1464 return spvType;
1465}
1466
John Kessenich5e4b1242015-08-06 22:53:06 -06001467// Given a member type of a struct, realign the current offset for it, and compute
1468// the next (not yet aligned) offset for the next member, which will get aligned
1469// on the next call.
1470// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1471// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1472// -1 means a non-forced member offset (no decoration needed).
1473void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset)
1474{
1475 // this will get a positive value when deemed necessary
1476 nextOffset = -1;
1477
1478 bool forceOffset = structType.getQualifier().layoutPacking == glslang::ElpStd140 ||
1479 structType.getQualifier().layoutPacking == glslang::ElpStd430;
1480
1481 // override anything in currentOffset with user-set offset
1482 if (memberType.getQualifier().hasOffset())
1483 currentOffset = memberType.getQualifier().layoutOffset;
1484
1485 // It could be that current linker usage in glslang updated all the layoutOffset,
1486 // in which case the following code does not matter. But, that's not quite right
1487 // once cross-compilation unit GLSL validation is done, as the original user
1488 // settings are needed in layoutOffset, and then the following will come into play.
1489
1490 if (! forceOffset) {
1491 if (! memberType.getQualifier().hasOffset())
1492 currentOffset = -1;
1493
1494 return;
1495 }
1496
1497 // Getting this far means we are forcing offsets
1498 if (currentOffset < 0)
1499 currentOffset = 0;
1500
1501 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1502 // but possibly not yet correctly aligned.
1503
1504 int memberSize;
1505 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, memberType.getQualifier().layoutPacking == glslang::ElpStd140);
1506 glslang::RoundToPow2(currentOffset, memberAlignment);
1507 nextOffset = currentOffset + memberSize;
1508}
1509
John Kessenich140f3df2015-06-26 16:58:36 -06001510bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1511{
1512 return node->getName() == "main(";
1513}
1514
1515// Make all the functions, skeletally, without actually visiting their bodies.
1516void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1517{
1518 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1519 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1520 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1521 continue;
1522
1523 // We're on a user function. Set up the basic interface for the function now,
1524 // so that it's available to call.
1525 // Translating the body will happen later.
1526 //
1527 // Typically (except for a "const in" parameter), an address will be passed to the
1528 // function. What it is an address of varies:
1529 //
1530 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1531 // so that write needs to be to a copy, hence the address of a copy works.
1532 //
1533 // - "const in" parameters can just be the r-value, as no writes need occur.
1534 //
1535 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1536 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1537
1538 std::vector<spv::Id> paramTypes;
1539 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1540
1541 for (int p = 0; p < (int)parameters.size(); ++p) {
1542 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1543 spv::Id typeId = convertGlslangToSpvType(paramType);
1544 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1545 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1546 else
1547 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1548 paramTypes.push_back(typeId);
1549 }
1550
1551 spv::Block* functionBlock;
1552 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1553 paramTypes, &functionBlock);
1554
1555 // Track function to emit/call later
1556 functionMap[glslFunction->getName().c_str()] = function;
1557
1558 // Set the parameter id's
1559 for (int p = 0; p < (int)parameters.size(); ++p) {
1560 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1561 // give a name too
1562 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1563 }
1564 }
1565}
1566
1567// Process all the initializers, while skipping the functions and link objects
1568void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1569{
1570 builder.setBuildPoint(shaderEntry->getLastBlock());
1571 for (int i = 0; i < (int)initializers.size(); ++i) {
1572 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1573 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1574
1575 // We're on a top-level node that's not a function. Treat as an initializer, whose
1576 // code goes into the beginning of main.
1577 initializer->traverse(this);
1578 }
1579 }
1580}
1581
1582// Process all the functions, while skipping initializers.
1583void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1584{
1585 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1586 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1587 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1588 node->traverse(this);
1589 }
1590}
1591
1592void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1593{
1594 // SPIR-V functions should already be in the functionMap from the prepass
1595 // that called makeFunctions().
1596 spv::Function* function = functionMap[node->getName().c_str()];
1597 spv::Block* functionBlock = function->getEntryBlock();
1598 builder.setBuildPoint(functionBlock);
1599}
1600
1601void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermSequence& glslangArguments, std::vector<spv::Id>& arguments)
1602{
1603 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1604 builder.clearAccessChain();
1605 glslangArguments[i]->traverse(this);
1606 arguments.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangArguments[i]->getAsTyped()->getType())));
1607 }
1608}
1609
John Kessenichfc51d282015-08-19 13:34:18 -06001610void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001611{
John Kessenichfc51d282015-08-19 13:34:18 -06001612 builder.clearAccessChain();
1613 node.getOperand()->traverse(this);
1614 arguments.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(node.getAsTyped()->getType())));
1615}
John Kessenich140f3df2015-06-26 16:58:36 -06001616
John Kessenichfc51d282015-08-19 13:34:18 -06001617spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1618{
1619 if (node->isImage()) {
1620 spv::MissingFunctionality("GLSL image function");
1621 return spv::NoResult;
1622 } else if (! node->isTexture()) {
1623 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001624 }
1625
John Kessenichfc51d282015-08-19 13:34:18 -06001626 // Process a GLSL texturing op (will be SPV image)
John Kessenich140f3df2015-06-26 16:58:36 -06001627
John Kessenichfc51d282015-08-19 13:34:18 -06001628 glslang::TCrackedTextureOp cracked;
1629 node->crackTexture(cracked);
1630
1631 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1632 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1633 std::vector<spv::Id> arguments;
1634 if (node->getAsAggregate())
1635 translateArguments(node->getAsAggregate()->getSequence(), arguments);
1636 else
1637 translateArguments(*node->getAsUnaryNode(), arguments);
1638 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1639
1640 spv::Builder::TextureParameters params = { };
1641 params.sampler = arguments[0];
1642
1643 // Check for queries
1644 if (cracked.query) {
1645 switch (node->getOp()) {
1646 case glslang::EOpImageQuerySize:
1647 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001648 if (arguments.size() > 1) {
1649 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001650 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001651 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001652 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001653 case glslang::EOpImageQuerySamples:
1654 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001655 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001656 case glslang::EOpTextureQueryLod:
1657 params.coords = arguments[1];
1658 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1659 case glslang::EOpTextureQueryLevels:
1660 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1661 default:
1662 assert(0);
1663 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001664 }
John Kessenich140f3df2015-06-26 16:58:36 -06001665 }
1666
John Kessenichfc51d282015-08-19 13:34:18 -06001667 // This is no longer a query....
John Kessenich140f3df2015-06-26 16:58:36 -06001668
John Kessenichfc51d282015-08-19 13:34:18 -06001669 if (cracked.gather)
1670 spv::MissingFunctionality("texture gather");
1671
1672 // check for bias argument
1673 bool bias = false;
1674 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch) {
1675 int nonBiasArgCount = 2;
1676 if (cracked.offset)
1677 ++nonBiasArgCount;
1678 if (cracked.grad)
1679 nonBiasArgCount += 2;
1680
1681 if ((int)arguments.size() > nonBiasArgCount)
1682 bias = true;
1683 }
1684
1685 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1686
1687 // set the rest of the arguments
1688 params.coords = arguments[1];
1689 int extraArgs = 0;
1690 if (cubeCompare)
1691 params.Dref = arguments[2];
1692 else if (sampler.shadow) {
1693 std::vector<spv::Id> indexes;
1694 int comp;
1695 if (cracked.proj)
1696 comp = 3;
1697 else
1698 comp = builder.getNumComponents(params.coords) - 1;
1699 indexes.push_back(comp);
1700 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1701 }
1702 if (cracked.lod) {
1703 params.lod = arguments[2];
1704 ++extraArgs;
1705 }
1706 if (cracked.grad) {
1707 params.gradX = arguments[2 + extraArgs];
1708 params.gradY = arguments[3 + extraArgs];
1709 extraArgs += 2;
1710 }
1711 //if (gather && compare) {
1712 // params.compare = arguments[2 + extraArgs];
1713 // ++extraArgs;
1714 //}
1715 if (cracked.offset || cracked.offsets) {
1716 params.offset = arguments[2 + extraArgs];
1717 ++extraArgs;
1718 }
1719 if (bias) {
1720 params.bias = arguments[2 + extraArgs];
1721 ++extraArgs;
1722 }
1723
Jason Ekstrand18b9fbd2015-09-05 14:14:48 -07001724 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001725}
1726
1727spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
1728{
1729 // Grab the function's pointer from the previously created function
1730 spv::Function* function = functionMap[node->getName().c_str()];
1731 if (! function)
1732 return 0;
1733
1734 const glslang::TIntermSequence& glslangArgs = node->getSequence();
1735 const glslang::TQualifierList& qualifiers = node->getQualifierList();
1736
1737 // See comments in makeFunctions() for details about the semantics for parameter passing.
1738 //
1739 // These imply we need a four step process:
1740 // 1. Evaluate the arguments
1741 // 2. Allocate and make copies of in, out, and inout arguments
1742 // 3. Make the call
1743 // 4. Copy back the results
1744
1745 // 1. Evaluate the arguments
1746 std::vector<spv::Builder::AccessChain> lValues;
1747 std::vector<spv::Id> rValues;
1748 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1749 // build l-value
1750 builder.clearAccessChain();
1751 glslangArgs[a]->traverse(this);
1752 // keep outputs as l-values, evaluate input-only as r-values
1753 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1754 // save l-value
1755 lValues.push_back(builder.getAccessChain());
1756 } else {
1757 // process r-value
1758 rValues.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangArgs[a]->getAsTyped()->getType())));
1759 }
1760 }
1761
1762 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
1763 // copy the original into that space.
1764 //
1765 // Also, build up the list of actual arguments to pass in for the call
1766 int lValueCount = 0;
1767 int rValueCount = 0;
1768 std::vector<spv::Id> spvArgs;
1769 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1770 spv::Id arg;
1771 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1772 // need space to hold the copy
1773 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
1774 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
1775 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
1776 // need to copy the input into output space
1777 builder.setAccessChain(lValues[lValueCount]);
1778 spv::Id copy = builder.accessChainLoad(spv::NoPrecision); // TODO: get precision
1779 builder.createStore(copy, arg);
1780 }
1781 ++lValueCount;
1782 } else {
1783 arg = rValues[rValueCount];
1784 ++rValueCount;
1785 }
1786 spvArgs.push_back(arg);
1787 }
1788
1789 // 3. Make the call.
1790 spv::Id result = builder.createFunctionCall(function, spvArgs);
1791
1792 // 4. Copy back out an "out" arguments.
1793 lValueCount = 0;
1794 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1795 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1796 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
1797 spv::Id copy = builder.createLoad(spvArgs[a]);
1798 builder.setAccessChain(lValues[lValueCount]);
1799 builder.accessChainStore(copy);
1800 }
1801 ++lValueCount;
1802 }
1803 }
1804
1805 return result;
1806}
1807
1808// Translate AST operation to SPV operation, already having SPV-based operands/types.
1809spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
1810 spv::Id typeId, spv::Id left, spv::Id right,
1811 glslang::TBasicType typeProxy, bool reduceComparison)
1812{
1813 bool isUnsigned = typeProxy == glslang::EbtUint;
1814 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
1815
1816 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06001817 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06001818 bool comparison = false;
1819
1820 switch (op) {
1821 case glslang::EOpAdd:
1822 case glslang::EOpAddAssign:
1823 if (isFloat)
1824 binOp = spv::OpFAdd;
1825 else
1826 binOp = spv::OpIAdd;
1827 break;
1828 case glslang::EOpSub:
1829 case glslang::EOpSubAssign:
1830 if (isFloat)
1831 binOp = spv::OpFSub;
1832 else
1833 binOp = spv::OpISub;
1834 break;
1835 case glslang::EOpMul:
1836 case glslang::EOpMulAssign:
1837 if (isFloat)
1838 binOp = spv::OpFMul;
1839 else
1840 binOp = spv::OpIMul;
1841 break;
1842 case glslang::EOpVectorTimesScalar:
1843 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06001844 if (isFloat) {
1845 if (builder.isVector(right))
1846 std::swap(left, right);
1847 assert(builder.isScalar(right));
1848 needMatchingVectors = false;
1849 binOp = spv::OpVectorTimesScalar;
1850 } else
1851 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06001852 break;
1853 case glslang::EOpVectorTimesMatrix:
1854 case glslang::EOpVectorTimesMatrixAssign:
1855 assert(builder.isVector(left));
1856 assert(builder.isMatrix(right));
1857 binOp = spv::OpVectorTimesMatrix;
1858 break;
1859 case glslang::EOpMatrixTimesVector:
1860 assert(builder.isMatrix(left));
1861 assert(builder.isVector(right));
1862 binOp = spv::OpMatrixTimesVector;
1863 break;
1864 case glslang::EOpMatrixTimesScalar:
1865 case glslang::EOpMatrixTimesScalarAssign:
1866 if (builder.isMatrix(right))
1867 std::swap(left, right);
1868 assert(builder.isScalar(right));
1869 binOp = spv::OpMatrixTimesScalar;
1870 break;
1871 case glslang::EOpMatrixTimesMatrix:
1872 case glslang::EOpMatrixTimesMatrixAssign:
1873 assert(builder.isMatrix(left));
1874 assert(builder.isMatrix(right));
1875 binOp = spv::OpMatrixTimesMatrix;
1876 break;
1877 case glslang::EOpOuterProduct:
1878 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06001879 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001880 break;
1881
1882 case glslang::EOpDiv:
1883 case glslang::EOpDivAssign:
1884 if (isFloat)
1885 binOp = spv::OpFDiv;
1886 else if (isUnsigned)
1887 binOp = spv::OpUDiv;
1888 else
1889 binOp = spv::OpSDiv;
1890 break;
1891 case glslang::EOpMod:
1892 case glslang::EOpModAssign:
1893 if (isFloat)
1894 binOp = spv::OpFMod;
1895 else if (isUnsigned)
1896 binOp = spv::OpUMod;
1897 else
1898 binOp = spv::OpSMod;
1899 break;
1900 case glslang::EOpRightShift:
1901 case glslang::EOpRightShiftAssign:
1902 if (isUnsigned)
1903 binOp = spv::OpShiftRightLogical;
1904 else
1905 binOp = spv::OpShiftRightArithmetic;
1906 break;
1907 case glslang::EOpLeftShift:
1908 case glslang::EOpLeftShiftAssign:
1909 binOp = spv::OpShiftLeftLogical;
1910 break;
1911 case glslang::EOpAnd:
1912 case glslang::EOpAndAssign:
1913 binOp = spv::OpBitwiseAnd;
1914 break;
1915 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06001916 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001917 binOp = spv::OpLogicalAnd;
1918 break;
1919 case glslang::EOpInclusiveOr:
1920 case glslang::EOpInclusiveOrAssign:
1921 binOp = spv::OpBitwiseOr;
1922 break;
1923 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06001924 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001925 binOp = spv::OpLogicalOr;
1926 break;
1927 case glslang::EOpExclusiveOr:
1928 case glslang::EOpExclusiveOrAssign:
1929 binOp = spv::OpBitwiseXor;
1930 break;
1931 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06001932 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06001933 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06001934 break;
1935
1936 case glslang::EOpLessThan:
1937 case glslang::EOpGreaterThan:
1938 case glslang::EOpLessThanEqual:
1939 case glslang::EOpGreaterThanEqual:
1940 case glslang::EOpEqual:
1941 case glslang::EOpNotEqual:
1942 case glslang::EOpVectorEqual:
1943 case glslang::EOpVectorNotEqual:
1944 comparison = true;
1945 break;
1946 default:
1947 break;
1948 }
1949
1950 if (binOp != spv::OpNop) {
1951 if (builder.isMatrix(left) || builder.isMatrix(right)) {
1952 switch (binOp) {
1953 case spv::OpMatrixTimesScalar:
1954 case spv::OpVectorTimesMatrix:
1955 case spv::OpMatrixTimesVector:
1956 case spv::OpMatrixTimesMatrix:
1957 break;
1958 case spv::OpFDiv:
1959 // turn it into a multiply...
1960 assert(builder.isMatrix(left) && builder.isScalar(right));
1961 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
1962 binOp = spv::OpFMul;
1963 break;
1964 default:
1965 spv::MissingFunctionality("binary operation on matrix");
1966 break;
1967 }
1968
1969 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
1970 builder.setPrecision(id, precision);
1971
1972 return id;
1973 }
1974
1975 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06001976 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06001977 builder.promoteScalar(precision, left, right);
1978
1979 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
1980 builder.setPrecision(id, precision);
1981
1982 return id;
1983 }
1984
1985 if (! comparison)
1986 return 0;
1987
1988 // Comparison instructions
1989
1990 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
1991 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
1992
1993 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
1994 }
1995
1996 switch (op) {
1997 case glslang::EOpLessThan:
1998 if (isFloat)
1999 binOp = spv::OpFOrdLessThan;
2000 else if (isUnsigned)
2001 binOp = spv::OpULessThan;
2002 else
2003 binOp = spv::OpSLessThan;
2004 break;
2005 case glslang::EOpGreaterThan:
2006 if (isFloat)
2007 binOp = spv::OpFOrdGreaterThan;
2008 else if (isUnsigned)
2009 binOp = spv::OpUGreaterThan;
2010 else
2011 binOp = spv::OpSGreaterThan;
2012 break;
2013 case glslang::EOpLessThanEqual:
2014 if (isFloat)
2015 binOp = spv::OpFOrdLessThanEqual;
2016 else if (isUnsigned)
2017 binOp = spv::OpULessThanEqual;
2018 else
2019 binOp = spv::OpSLessThanEqual;
2020 break;
2021 case glslang::EOpGreaterThanEqual:
2022 if (isFloat)
2023 binOp = spv::OpFOrdGreaterThanEqual;
2024 else if (isUnsigned)
2025 binOp = spv::OpUGreaterThanEqual;
2026 else
2027 binOp = spv::OpSGreaterThanEqual;
2028 break;
2029 case glslang::EOpEqual:
2030 case glslang::EOpVectorEqual:
2031 if (isFloat)
2032 binOp = spv::OpFOrdEqual;
2033 else
2034 binOp = spv::OpIEqual;
2035 break;
2036 case glslang::EOpNotEqual:
2037 case glslang::EOpVectorNotEqual:
2038 if (isFloat)
2039 binOp = spv::OpFOrdNotEqual;
2040 else
2041 binOp = spv::OpINotEqual;
2042 break;
2043 default:
2044 break;
2045 }
2046
2047 if (binOp != spv::OpNop) {
2048 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2049 builder.setPrecision(id, precision);
2050
2051 return id;
2052 }
2053
2054 return 0;
2055}
2056
2057spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, bool isFloat)
2058{
2059 spv::Op unaryOp = spv::OpNop;
2060 int libCall = -1;
2061
2062 switch (op) {
2063 case glslang::EOpNegative:
2064 if (isFloat)
2065 unaryOp = spv::OpFNegate;
2066 else
2067 unaryOp = spv::OpSNegate;
2068 break;
2069
2070 case glslang::EOpLogicalNot:
2071 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002072 unaryOp = spv::OpLogicalNot;
2073 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002074 case glslang::EOpBitwiseNot:
2075 unaryOp = spv::OpNot;
2076 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002077
John Kessenich140f3df2015-06-26 16:58:36 -06002078 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002079 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002080 break;
2081 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002082 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002083 break;
2084 case glslang::EOpTranspose:
2085 unaryOp = spv::OpTranspose;
2086 break;
2087
2088 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002089 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002090 break;
2091 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002092 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002093 break;
2094 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002095 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002096 break;
2097 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002098 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002099 break;
2100 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002101 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002102 break;
2103 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002104 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002105 break;
2106 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002107 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002108 break;
2109 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002110 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002111 break;
2112
2113 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002114 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002115 break;
2116 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002117 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002118 break;
2119 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002120 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002121 break;
2122 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002123 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002124 break;
2125 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002126 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002127 break;
2128 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002129 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002130 break;
2131
2132 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002133 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002134 break;
2135 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002136 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002137 break;
2138
2139 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002140 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002141 break;
2142 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002143 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002144 break;
2145 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002146 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002147 break;
2148 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002149 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002150 break;
2151 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002152 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002153 break;
2154 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002155 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002156 break;
2157
2158 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002159 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002160 break;
2161 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002162 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002163 break;
2164 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002165 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002166 break;
2167 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002168 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002169 break;
2170 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002171 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002172 break;
2173 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002174 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002175 break;
2176
2177 case glslang::EOpIsNan:
2178 unaryOp = spv::OpIsNan;
2179 break;
2180 case glslang::EOpIsInf:
2181 unaryOp = spv::OpIsInf;
2182 break;
2183
John Kessenich140f3df2015-06-26 16:58:36 -06002184 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002185 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002186 break;
2187 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002188 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002189 break;
2190 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002191 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002192 break;
2193 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002194 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002195 break;
2196 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002197 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002198 break;
2199 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002200 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002201 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002202 case glslang::EOpPackSnorm4x8:
2203 libCall = spv::GLSLstd450PackSnorm4x8;
2204 break;
2205 case glslang::EOpUnpackSnorm4x8:
2206 libCall = spv::GLSLstd450UnpackSnorm4x8;
2207 break;
2208 case glslang::EOpPackUnorm4x8:
2209 libCall = spv::GLSLstd450PackUnorm4x8;
2210 break;
2211 case glslang::EOpUnpackUnorm4x8:
2212 libCall = spv::GLSLstd450UnpackUnorm4x8;
2213 break;
2214 case glslang::EOpPackDouble2x32:
2215 libCall = spv::GLSLstd450PackDouble2x32;
2216 break;
2217 case glslang::EOpUnpackDouble2x32:
2218 libCall = spv::GLSLstd450UnpackDouble2x32;
2219 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002220
2221 case glslang::EOpDPdx:
2222 unaryOp = spv::OpDPdx;
2223 break;
2224 case glslang::EOpDPdy:
2225 unaryOp = spv::OpDPdy;
2226 break;
2227 case glslang::EOpFwidth:
2228 unaryOp = spv::OpFwidth;
2229 break;
2230 case glslang::EOpDPdxFine:
2231 unaryOp = spv::OpDPdxFine;
2232 break;
2233 case glslang::EOpDPdyFine:
2234 unaryOp = spv::OpDPdyFine;
2235 break;
2236 case glslang::EOpFwidthFine:
2237 unaryOp = spv::OpFwidthFine;
2238 break;
2239 case glslang::EOpDPdxCoarse:
2240 unaryOp = spv::OpDPdxCoarse;
2241 break;
2242 case glslang::EOpDPdyCoarse:
2243 unaryOp = spv::OpDPdyCoarse;
2244 break;
2245 case glslang::EOpFwidthCoarse:
2246 unaryOp = spv::OpFwidthCoarse;
2247 break;
2248
2249 case glslang::EOpAny:
2250 unaryOp = spv::OpAny;
2251 break;
2252 case glslang::EOpAll:
2253 unaryOp = spv::OpAll;
2254 break;
2255
2256 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002257 if (isFloat)
2258 libCall = spv::GLSLstd450FAbs;
2259 else
2260 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002261 break;
2262 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002263 if (isFloat)
2264 libCall = spv::GLSLstd450FSign;
2265 else
2266 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002267 break;
2268
John Kessenichfc51d282015-08-19 13:34:18 -06002269 case glslang::EOpAtomicCounterIncrement:
2270 case glslang::EOpAtomicCounterDecrement:
2271 case glslang::EOpAtomicCounter:
2272 {
2273 // Handle all of the atomics in one place, in createAtomicOperation()
2274 std::vector<spv::Id> operands;
2275 operands.push_back(operand);
2276 return createAtomicOperation(op, precision, typeId, operands);
2277 }
2278
2279 case glslang::EOpImageLoad:
2280 unaryOp = spv::OpImageRead;
2281 break;
2282
2283 case glslang::EOpBitFieldReverse:
2284 unaryOp = spv::OpBitReverse;
2285 break;
2286 case glslang::EOpBitCount:
2287 unaryOp = spv::OpBitCount;
2288 break;
2289 case glslang::EOpFindLSB:
2290 libCall = spv::GLSLstd450FindILSB;
2291 break;
2292 case glslang::EOpFindMSB:
2293 spv::MissingFunctionality("signed vs. unsigned FindMSB");
2294 libCall = spv::GLSLstd450FindSMSB;
2295 break;
2296
John Kessenich140f3df2015-06-26 16:58:36 -06002297 default:
2298 return 0;
2299 }
2300
2301 spv::Id id;
2302 if (libCall >= 0) {
2303 std::vector<spv::Id> args;
2304 args.push_back(operand);
2305 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2306 } else
2307 id = builder.createUnaryOp(unaryOp, typeId, operand);
2308
2309 builder.setPrecision(id, precision);
2310
2311 return id;
2312}
2313
2314spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2315{
2316 spv::Op convOp = spv::OpNop;
2317 spv::Id zero = 0;
2318 spv::Id one = 0;
2319
2320 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2321
2322 switch (op) {
2323 case glslang::EOpConvIntToBool:
2324 case glslang::EOpConvUintToBool:
2325 zero = builder.makeUintConstant(0);
2326 zero = makeSmearedConstant(zero, vectorSize);
2327 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2328
2329 case glslang::EOpConvFloatToBool:
2330 zero = builder.makeFloatConstant(0.0F);
2331 zero = makeSmearedConstant(zero, vectorSize);
2332 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2333
2334 case glslang::EOpConvDoubleToBool:
2335 zero = builder.makeDoubleConstant(0.0);
2336 zero = makeSmearedConstant(zero, vectorSize);
2337 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2338
2339 case glslang::EOpConvBoolToFloat:
2340 convOp = spv::OpSelect;
2341 zero = builder.makeFloatConstant(0.0);
2342 one = builder.makeFloatConstant(1.0);
2343 break;
2344 case glslang::EOpConvBoolToDouble:
2345 convOp = spv::OpSelect;
2346 zero = builder.makeDoubleConstant(0.0);
2347 one = builder.makeDoubleConstant(1.0);
2348 break;
2349 case glslang::EOpConvBoolToInt:
2350 zero = builder.makeIntConstant(0);
2351 one = builder.makeIntConstant(1);
2352 convOp = spv::OpSelect;
2353 break;
2354 case glslang::EOpConvBoolToUint:
2355 zero = builder.makeUintConstant(0);
2356 one = builder.makeUintConstant(1);
2357 convOp = spv::OpSelect;
2358 break;
2359
2360 case glslang::EOpConvIntToFloat:
2361 case glslang::EOpConvIntToDouble:
2362 convOp = spv::OpConvertSToF;
2363 break;
2364
2365 case glslang::EOpConvUintToFloat:
2366 case glslang::EOpConvUintToDouble:
2367 convOp = spv::OpConvertUToF;
2368 break;
2369
2370 case glslang::EOpConvDoubleToFloat:
2371 case glslang::EOpConvFloatToDouble:
2372 convOp = spv::OpFConvert;
2373 break;
2374
2375 case glslang::EOpConvFloatToInt:
2376 case glslang::EOpConvDoubleToInt:
2377 convOp = spv::OpConvertFToS;
2378 break;
2379
2380 case glslang::EOpConvUintToInt:
2381 case glslang::EOpConvIntToUint:
2382 convOp = spv::OpBitcast;
2383 break;
2384
2385 case glslang::EOpConvFloatToUint:
2386 case glslang::EOpConvDoubleToUint:
2387 convOp = spv::OpConvertFToU;
2388 break;
2389 default:
2390 break;
2391 }
2392
2393 spv::Id result = 0;
2394 if (convOp == spv::OpNop)
2395 return result;
2396
2397 if (convOp == spv::OpSelect) {
2398 zero = makeSmearedConstant(zero, vectorSize);
2399 one = makeSmearedConstant(one, vectorSize);
2400 result = builder.createTriOp(convOp, destType, operand, one, zero);
2401 } else
2402 result = builder.createUnaryOp(convOp, destType, operand);
2403
2404 builder.setPrecision(result, precision);
2405
2406 return result;
2407}
2408
2409spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2410{
2411 if (vectorSize == 0)
2412 return constant;
2413
2414 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2415 std::vector<spv::Id> components;
2416 for (int c = 0; c < vectorSize; ++c)
2417 components.push_back(constant);
2418 return builder.makeCompositeConstant(vectorTypeId, components);
2419}
2420
John Kessenich426394d2015-07-23 10:22:48 -06002421// For glslang ops that map to SPV atomic opCodes
2422spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands)
2423{
2424 spv::Op opCode = spv::OpNop;
2425
2426 switch (op) {
2427 case glslang::EOpAtomicAdd:
2428 opCode = spv::OpAtomicIAdd;
2429 break;
2430 case glslang::EOpAtomicMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002431 opCode = spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002432 break;
2433 case glslang::EOpAtomicMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002434 opCode = spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002435 break;
2436 case glslang::EOpAtomicAnd:
2437 opCode = spv::OpAtomicAnd;
2438 break;
2439 case glslang::EOpAtomicOr:
2440 opCode = spv::OpAtomicOr;
2441 break;
2442 case glslang::EOpAtomicXor:
2443 opCode = spv::OpAtomicXor;
2444 break;
2445 case glslang::EOpAtomicExchange:
2446 opCode = spv::OpAtomicExchange;
2447 break;
2448 case glslang::EOpAtomicCompSwap:
2449 opCode = spv::OpAtomicCompareExchange;
2450 break;
2451 case glslang::EOpAtomicCounterIncrement:
2452 opCode = spv::OpAtomicIIncrement;
2453 break;
2454 case glslang::EOpAtomicCounterDecrement:
2455 opCode = spv::OpAtomicIDecrement;
2456 break;
2457 case glslang::EOpAtomicCounter:
2458 opCode = spv::OpAtomicLoad;
2459 break;
2460 default:
2461 spv::MissingFunctionality("missing nested atomic");
2462 break;
2463 }
2464
2465 // Sort out the operands
2466 // - mapping from glslang -> SPV
2467 // - there are extra SPV operands with no glslang source
2468 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2469 auto opIt = operands.begin(); // walk the glslang operands
2470 spvAtomicOperands.push_back(*(opIt++));
John Kessenich5e4b1242015-08-06 22:53:06 -06002471 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2472 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
John Kessenich426394d2015-07-23 10:22:48 -06002473
2474 // Add the rest of the operands, skipping the first one, which was dealt with above.
2475 // For some ops, there are none, for some 1, for compare-exchange, 2.
2476 for (; opIt != operands.end(); ++opIt)
2477 spvAtomicOperands.push_back(*opIt);
2478
2479 return builder.createOp(opCode, typeId, spvAtomicOperands);
2480}
2481
John Kessenich5e4b1242015-08-06 22:53:06 -06002482spv::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 -06002483{
John Kessenich5e4b1242015-08-06 22:53:06 -06002484 bool isUnsigned = typeProxy == glslang::EbtUint;
2485 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2486
John Kessenich140f3df2015-06-26 16:58:36 -06002487 spv::Op opCode = spv::OpNop;
2488 int libCall = -1;
2489
2490 switch (op) {
2491 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002492 if (isFloat)
2493 libCall = spv::GLSLstd450FMin;
2494 else if (isUnsigned)
2495 libCall = spv::GLSLstd450UMin;
2496 else
2497 libCall = spv::GLSLstd450SMin;
John Kessenich140f3df2015-06-26 16:58:36 -06002498 break;
2499 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002500 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002501 break;
2502 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002503 if (isFloat)
2504 libCall = spv::GLSLstd450FMax;
2505 else if (isUnsigned)
2506 libCall = spv::GLSLstd450UMax;
2507 else
2508 libCall = spv::GLSLstd450SMax;
John Kessenich140f3df2015-06-26 16:58:36 -06002509 break;
2510 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002511 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002512 break;
2513 case glslang::EOpDot:
2514 opCode = spv::OpDot;
2515 break;
2516 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002517 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002518 break;
2519
2520 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002521 if (isFloat)
2522 libCall = spv::GLSLstd450FClamp;
2523 else if (isUnsigned)
2524 libCall = spv::GLSLstd450UClamp;
2525 else
2526 libCall = spv::GLSLstd450SClamp;
John Kessenich140f3df2015-06-26 16:58:36 -06002527 break;
2528 case glslang::EOpMix:
John Kessenich5e4b1242015-08-06 22:53:06 -06002529 libCall = spv::GLSLstd450Mix;
John Kessenich140f3df2015-06-26 16:58:36 -06002530 break;
2531 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002532 libCall = spv::GLSLstd450Step;
John Kessenich140f3df2015-06-26 16:58:36 -06002533 break;
2534 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002535 libCall = spv::GLSLstd450SmoothStep;
John Kessenich140f3df2015-06-26 16:58:36 -06002536 break;
2537
2538 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002539 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002540 break;
2541 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002542 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002543 break;
2544 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002545 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002546 break;
2547 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002548 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002549 break;
2550 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002551 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002552 break;
John Kessenich426394d2015-07-23 10:22:48 -06002553
John Kessenich140f3df2015-06-26 16:58:36 -06002554 default:
2555 return 0;
2556 }
2557
2558 spv::Id id = 0;
2559 if (libCall >= 0)
2560 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, operands);
2561 else {
2562 switch (operands.size()) {
2563 case 0:
2564 // should all be handled by visitAggregate and createNoArgOperation
2565 assert(0);
2566 return 0;
2567 case 1:
2568 // should all be handled by createUnaryOperation
2569 assert(0);
2570 return 0;
2571 case 2:
2572 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
2573 break;
2574 case 3:
John Kessenich426394d2015-07-23 10:22:48 -06002575 id = builder.createTriOp(opCode, typeId, operands[0], operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002576 break;
2577 default:
2578 // These do not exist yet
2579 assert(0 && "operation with more than 3 operands");
2580 break;
2581 }
2582 }
2583
2584 builder.setPrecision(id, precision);
2585
2586 return id;
2587}
2588
2589// Intrinsics with no arguments, no return value, and no precision.
2590spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
2591{
2592 // TODO: get the barrier operands correct
2593
2594 switch (op) {
2595 case glslang::EOpEmitVertex:
2596 builder.createNoResultOp(spv::OpEmitVertex);
2597 return 0;
2598 case glslang::EOpEndPrimitive:
2599 builder.createNoResultOp(spv::OpEndPrimitive);
2600 return 0;
2601 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002602 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
2603 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06002604 return 0;
2605 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002606 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06002607 return 0;
2608 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06002609 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002610 return 0;
2611 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06002612 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002613 return 0;
2614 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06002615 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002616 return 0;
2617 case glslang::EOpMemoryBarrierShared:
John Kessenich5e4b1242015-08-06 22:53:06 -06002618 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupLocalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002619 return 0;
2620 case glslang::EOpGroupMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002621 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupGlobalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002622 return 0;
2623 default:
2624 spv::MissingFunctionality("operation with no arguments");
2625 return 0;
2626 }
2627}
2628
2629spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
2630{
John Kessenich2f273362015-07-18 22:34:27 -06002631 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06002632 spv::Id id;
2633 if (symbolValues.end() != iter) {
2634 id = iter->second;
2635 return id;
2636 }
2637
2638 // it was not found, create it
2639 id = createSpvVariable(symbol);
2640 symbolValues[symbol->getId()] = id;
2641
2642 if (! symbol->getType().isStruct()) {
2643 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
2644 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
2645 if (symbol->getQualifier().hasLocation())
2646 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
2647 if (symbol->getQualifier().hasIndex())
2648 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
2649 if (symbol->getQualifier().hasComponent())
2650 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
2651 if (glslangIntermediate->getXfbMode()) {
2652 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002653 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002654 if (symbol->getQualifier().hasXfbBuffer())
2655 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2656 if (symbol->getQualifier().hasXfbOffset())
2657 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
2658 }
2659 }
2660
2661 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
2662 if (symbol->getQualifier().hasStream())
2663 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
2664 if (symbol->getQualifier().hasSet())
2665 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
2666 if (symbol->getQualifier().hasBinding())
2667 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
2668 if (glslangIntermediate->getXfbMode()) {
2669 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002670 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002671 if (symbol->getQualifier().hasXfbBuffer())
2672 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2673 }
2674
2675 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06002676 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06002677 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06002678 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06002679
2680 if (linkageOnly)
2681 builder.addDecoration(id, spv::DecorationNoStaticUse);
2682
2683 return id;
2684}
2685
2686void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
2687{
2688 if (dec != spv::BadValue)
2689 builder.addDecoration(id, dec);
2690}
2691
2692void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
2693{
2694 if (dec != spv::BadValue)
2695 builder.addMemberDecoration(id, (unsigned)member, dec);
2696}
2697
2698// Use 'consts' as the flattened glslang source of scalar constants to recursively
2699// build the aggregate SPIR-V constant.
2700//
2701// If there are not enough elements present in 'consts', 0 will be substituted;
2702// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
2703//
2704spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst)
2705{
2706 // vector of constants for SPIR-V
2707 std::vector<spv::Id> spvConsts;
2708
2709 // Type is used for struct and array constants
2710 spv::Id typeId = convertGlslangToSpvType(glslangType);
2711
2712 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002713 glslang::TType elementType(glslangType, 0);
2714 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich140f3df2015-06-26 16:58:36 -06002715 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst));
2716 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002717 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06002718 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
2719 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst));
2720 } else if (glslangType.getStruct()) {
2721 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
2722 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
2723 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst));
2724 } else if (glslangType.isVector()) {
2725 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
2726 bool zero = nextConst >= consts.size();
2727 switch (glslangType.getBasicType()) {
2728 case glslang::EbtInt:
2729 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
2730 break;
2731 case glslang::EbtUint:
2732 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
2733 break;
2734 case glslang::EbtFloat:
2735 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
2736 break;
2737 case glslang::EbtDouble:
2738 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
2739 break;
2740 case glslang::EbtBool:
2741 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
2742 break;
2743 default:
2744 spv::MissingFunctionality("constant vector type");
2745 break;
2746 }
2747 ++nextConst;
2748 }
2749 } else {
2750 // we have a non-aggregate (scalar) constant
2751 bool zero = nextConst >= consts.size();
2752 spv::Id scalar = 0;
2753 switch (glslangType.getBasicType()) {
2754 case glslang::EbtInt:
2755 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst());
2756 break;
2757 case glslang::EbtUint:
2758 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst());
2759 break;
2760 case glslang::EbtFloat:
2761 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst());
2762 break;
2763 case glslang::EbtDouble:
2764 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst());
2765 break;
2766 case glslang::EbtBool:
2767 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst());
2768 break;
2769 default:
2770 spv::MissingFunctionality("constant scalar type");
2771 break;
2772 }
2773 ++nextConst;
2774 return scalar;
2775 }
2776
2777 return builder.makeCompositeConstant(typeId, spvConsts);
2778}
2779
2780}; // end anonymous namespace
2781
2782namespace glslang {
2783
John Kessenich68d78fd2015-07-12 19:28:10 -06002784void GetSpirvVersion(std::string& version)
2785{
John Kessenich9e55f632015-07-15 10:03:39 -06002786 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06002787 char buf[bufSize];
John Kessenich9e55f632015-07-15 10:03:39 -06002788 snprintf(buf, bufSize, "%d, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06002789 version = buf;
2790}
2791
John Kessenich140f3df2015-06-26 16:58:36 -06002792// Write SPIR-V out to a binary file
2793void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
2794{
2795 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06002796 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06002797 for (int i = 0; i < (int)spirv.size(); ++i) {
2798 unsigned int word = spirv[i];
2799 out.write((const char*)&word, 4);
2800 }
2801 out.close();
2802}
2803
2804//
2805// Set up the glslang traversal
2806//
2807void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
2808{
2809 TIntermNode* root = intermediate.getTreeRoot();
2810
2811 if (root == 0)
2812 return;
2813
2814 glslang::GetThreadPoolAllocator().push();
2815
2816 TGlslangToSpvTraverser it(&intermediate);
2817
2818 root->traverse(&it);
2819
2820 it.dumpSpv(spirv);
2821
2822 glslang::GetThreadPoolAllocator().pop();
2823}
2824
2825}; // end namespace glslang