blob: 3dffceb9760a9367e2ef963b97466d84cd2d6940 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
2//Copyright (C) 2014 LunarG, Inc.
3//
4//All rights reserved.
5//
6//Redistribution and use in source and binary forms, with or without
7//modification, are permitted provided that the following conditions
8//are met:
9//
10// Redistributions of source code must retain the above copyright
11// notice, this list of conditions and the following disclaimer.
12//
13// Redistributions in binary form must reproduce the above
14// copyright notice, this list of conditions and the following
15// disclaimer in the documentation and/or other materials provided
16// with the distribution.
17//
18// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
19// contributors may be used to endorse or promote products derived
20// from this software without specific prior written permission.
21//
22//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
32//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33//POSSIBILITY OF SUCH DAMAGE.
34
35//
36// Author: John Kessenich, LunarG
37//
38// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
46 #include "GLSL.std.450.h"
47}
John Kessenich140f3df2015-06-26 16:58:36 -060048
49// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020050#include "../glslang/MachineIndependent/localintermediate.h"
51#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060052#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060053
54#include <string>
55#include <map>
56#include <list>
57#include <vector>
58#include <stack>
59#include <fstream>
60
61namespace {
62
63const int GlslangMagic = 0x51a;
64
65//
66// The main holder of information for translating glslang to SPIR-V.
67//
68// Derives from the AST walking base class.
69//
70class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
71public:
72 TGlslangToSpvTraverser(const glslang::TIntermediate*);
73 virtual ~TGlslangToSpvTraverser();
74
75 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
76 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
77 void visitConstantUnion(glslang::TIntermConstantUnion*);
78 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
79 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
80 void visitSymbol(glslang::TIntermSymbol* symbol);
81 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
82 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
83 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
84
85 void dumpSpv(std::vector<unsigned int>& out) { builder.dump(out); }
86
87protected:
88 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
89 spv::Id getSampledType(const glslang::TSampler&);
90 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenich31ed4832015-09-09 17:51:38 -060091 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout);
92 bool requiresExplicitLayout(const glslang::TType& type) const;
Jason Ekstrand54aedf12015-09-05 09:50:58 -070093 int getArrayStride(const glslang::TType& arrayType);
94 int getMatrixStride(const glslang::TType& matrixType);
John Kessenich5e4b1242015-08-06 22:53:06 -060095 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset);
John Kessenich140f3df2015-06-26 16:58:36 -060096
97 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
98 void makeFunctions(const glslang::TIntermSequence&);
99 void makeGlobalInitializers(const glslang::TIntermSequence&);
100 void visitFunctions(const glslang::TIntermSequence&);
101 void handleFunctionEntry(const glslang::TIntermAggregate* node);
102 void translateArguments(const glslang::TIntermSequence& glslangArguments, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600103 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
104 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600105 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
106
107 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
108 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, bool isFloat);
109 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
110 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich426394d2015-07-23 10:22:48 -0600111 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600112 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600113 spv::Id createNoArgOperation(glslang::TOperator op);
114 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
115 void addDecoration(spv::Id id, spv::Decoration dec);
116 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
117 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst);
118
119 spv::Function* shaderEntry;
120 int sequenceDepth;
121
122 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
123 spv::Builder builder;
124 bool inMain;
125 bool mainTerminated;
126 bool linkageOnly;
127 const glslang::TIntermediate* glslangIntermediate;
128 spv::Id stdBuiltins;
129
John Kessenich2f273362015-07-18 22:34:27 -0600130 std::unordered_map<int, spv::Id> symbolValues;
131 std::unordered_set<int> constReadOnlyParameters; // set of formal function parameters that have glslang qualifier constReadOnly, so we know they are not local function "const" that are write-once
132 std::unordered_map<std::string, spv::Function*> functionMap;
133 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap;
134 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600135 std::stack<bool> breakForLoop; // false means break for switch
136 std::stack<glslang::TIntermTyped*> loopTerminal; // code from the last part of a for loop: for(...; ...; terminal), needed for e.g., continue };
137};
138
139//
140// Helper functions for translating glslang representations to SPIR-V enumerants.
141//
142
143// Translate glslang profile to SPIR-V source language.
144spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
145{
146 switch (profile) {
147 case ENoProfile:
148 case ECoreProfile:
149 case ECompatibilityProfile:
150 return spv::SourceLanguageGLSL;
151 case EEsProfile:
152 return spv::SourceLanguageESSL;
153 default:
154 return spv::SourceLanguageUnknown;
155 }
156}
157
158// Translate glslang language (stage) to SPIR-V execution model.
159spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
160{
161 switch (stage) {
162 case EShLangVertex: return spv::ExecutionModelVertex;
163 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
164 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
165 case EShLangGeometry: return spv::ExecutionModelGeometry;
166 case EShLangFragment: return spv::ExecutionModelFragment;
167 case EShLangCompute: return spv::ExecutionModelGLCompute;
168 default:
169 spv::MissingFunctionality("GLSL stage");
170 return spv::ExecutionModelFragment;
171 }
172}
173
174// Translate glslang type to SPIR-V storage class.
175spv::StorageClass TranslateStorageClass(const glslang::TType& type)
176{
177 if (type.getQualifier().isPipeInput())
178 return spv::StorageClassInput;
179 else if (type.getQualifier().isPipeOutput())
180 return spv::StorageClassOutput;
181 else if (type.getQualifier().isUniformOrBuffer()) {
182 if (type.getBasicType() == glslang::EbtBlock)
183 return spv::StorageClassUniform;
184 else
185 return spv::StorageClassUniformConstant;
186 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
187 } else {
188 switch (type.getQualifier().storage) {
189 case glslang::EvqShared: return spv::StorageClassWorkgroupLocal; break;
190 case glslang::EvqGlobal: return spv::StorageClassPrivateGlobal;
191 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
192 case glslang::EvqTemporary: return spv::StorageClassFunction;
193 default:
194 spv::MissingFunctionality("unknown glslang storage class");
195 return spv::StorageClassFunction;
196 }
197 }
198}
199
200// Translate glslang sampler type to SPIR-V dimensionality.
201spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
202{
203 switch (sampler.dim) {
204 case glslang::Esd1D: return spv::Dim1D;
205 case glslang::Esd2D: return spv::Dim2D;
206 case glslang::Esd3D: return spv::Dim3D;
207 case glslang::EsdCube: return spv::DimCube;
208 case glslang::EsdRect: return spv::DimRect;
209 case glslang::EsdBuffer: return spv::DimBuffer;
210 default:
211 spv::MissingFunctionality("unknown sampler dimension");
212 return spv::Dim2D;
213 }
214}
215
216// Translate glslang type to SPIR-V precision decorations.
217spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
218{
219 switch (type.getQualifier().precision) {
John Kessenich5e4b1242015-08-06 22:53:06 -0600220 case glslang::EpqLow: return spv::DecorationRelaxedPrecision; // TODO: Map instead to 16-bit types?
221 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
222 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600223 default:
224 return spv::NoPrecision;
225 }
226}
227
228// Translate glslang type to SPIR-V block decorations.
229spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
230{
231 if (type.getBasicType() == glslang::EbtBlock) {
232 switch (type.getQualifier().storage) {
233 case glslang::EvqUniform: return spv::DecorationBlock;
234 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
235 case glslang::EvqVaryingIn: return spv::DecorationBlock;
236 case glslang::EvqVaryingOut: return spv::DecorationBlock;
237 default:
238 spv::MissingFunctionality("kind of block");
239 break;
240 }
241 }
242
243 return (spv::Decoration)spv::BadValue;
244}
245
246// Translate glslang type to SPIR-V layout decorations.
247spv::Decoration TranslateLayoutDecoration(const glslang::TType& type)
248{
249 if (type.isMatrix()) {
250 switch (type.getQualifier().layoutMatrix) {
251 case glslang::ElmRowMajor:
252 return spv::DecorationRowMajor;
253 default:
254 return spv::DecorationColMajor;
255 }
256 } else {
257 switch (type.getBasicType()) {
258 default:
259 return (spv::Decoration)spv::BadValue;
260 break;
261 case glslang::EbtBlock:
262 switch (type.getQualifier().storage) {
263 case glslang::EvqUniform:
264 case glslang::EvqBuffer:
265 switch (type.getQualifier().layoutPacking) {
266 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600267 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
268 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600269 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600270 }
271 case glslang::EvqVaryingIn:
272 case glslang::EvqVaryingOut:
273 if (type.getQualifier().layoutPacking != glslang::ElpNone)
274 spv::MissingFunctionality("in/out block layout");
275 return (spv::Decoration)spv::BadValue;
276 default:
277 spv::MissingFunctionality("block storage qualification");
278 return (spv::Decoration)spv::BadValue;
279 }
280 }
281 }
282}
283
284// Translate glslang type to SPIR-V interpolation decorations.
285spv::Decoration TranslateInterpolationDecoration(const glslang::TType& type)
286{
287 if (type.getQualifier().smooth)
288 return spv::DecorationSmooth;
289 if (type.getQualifier().nopersp)
290 return spv::DecorationNoperspective;
291 else if (type.getQualifier().patch)
292 return spv::DecorationPatch;
293 else if (type.getQualifier().flat)
294 return spv::DecorationFlat;
295 else if (type.getQualifier().centroid)
296 return spv::DecorationCentroid;
297 else if (type.getQualifier().sample)
298 return spv::DecorationSample;
299 else
300 return (spv::Decoration)spv::BadValue;
301}
302
303// If glslang type is invaraiant, return SPIR-V invariant decoration.
304spv::Decoration TranslateInvariantDecoration(const glslang::TType& type)
305{
306 if (type.getQualifier().invariant)
307 return spv::DecorationInvariant;
308 else
309 return (spv::Decoration)spv::BadValue;
310}
311
312// Translate glslang built-in variable to SPIR-V built in decoration.
313spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
314{
315 switch (builtIn) {
316 case glslang::EbvPosition: return spv::BuiltInPosition;
317 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600318 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
319 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
320 case glslang::EbvVertexId: return spv::BuiltInVertexId;
321 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
322 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
323 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
324 case glslang::EbvLayer: return spv::BuiltInLayer;
325 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
326 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
327 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
328 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
329 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
330 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
331 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
332 case glslang::EbvFace: return spv::BuiltInFrontFacing;
333 case glslang::EbvSampleId: return spv::BuiltInSampleId;
334 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
335 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
336 case glslang::EbvFragColor: return spv::BuiltInFragColor;
337 case glslang::EbvFragData: return spv::BuiltInFragColor;
338 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
339 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
340 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
341 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
342 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
343 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
344 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
345 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
346 default: return (spv::BuiltIn)spv::BadValue;
347 }
348}
349
350//
351// Implement the TGlslangToSpvTraverser class.
352//
353
354TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
355 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
356 builder(GlslangMagic),
357 inMain(false), mainTerminated(false), linkageOnly(false),
358 glslangIntermediate(glslangIntermediate)
359{
360 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
361
362 builder.clearAccessChain();
363 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
364 stdBuiltins = builder.import("GLSL.std.450");
365 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
366 shaderEntry = builder.makeMain();
John Kessenich5e4b1242015-08-06 22:53:06 -0600367 builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600368
369 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600370 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
371 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600372 builder.addSourceExtension(it->c_str());
373
374 // Add the top-level modes for this shader.
375
376 if (glslangIntermediate->getXfbMode())
377 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
378
379 unsigned int mode;
380 switch (glslangIntermediate->getStage()) {
381 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600382 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600383 break;
384
385 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600386 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600387 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
388 break;
389
390 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600391 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600392 switch (glslangIntermediate->getInputPrimitive()) {
393 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
394 case glslang::ElgQuads: mode = spv::ExecutionModeInputQuads; break;
395 case glslang::ElgIsolines: mode = spv::ExecutionModeInputIsolines; break;
396 default: mode = spv::BadValue; break;
397 }
398 if (mode != spv::BadValue)
399 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
400
401 // TODO
402 //builder.addExecutionMode(spv::VertexSpacingMdName, glslangIntermediate->getVertexSpacing());
403 //builder.addExecutionMode(spv::VertexOrderMdName, glslangIntermediate->getVertexOrder());
404 //builder.addExecutionMode(spv::PointModeMdName, glslangIntermediate->getPointMode());
405 break;
406
407 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600408 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600409 switch (glslangIntermediate->getInputPrimitive()) {
410 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
411 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
412 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
413 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
414 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
415 default: mode = spv::BadValue; break;
416 }
417 if (mode != spv::BadValue)
418 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
419 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
420
421 switch (glslangIntermediate->getOutputPrimitive()) {
422 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
423 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
424 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
425 default: mode = spv::BadValue; break;
426 }
427 if (mode != spv::BadValue)
428 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
429 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
430 break;
431
432 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600433 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600434 if (glslangIntermediate->getPixelCenterInteger())
435 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
436 if (glslangIntermediate->getOriginUpperLeft())
437 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600438 else
439 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kessenich140f3df2015-06-26 16:58:36 -0600440 break;
441
442 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600443 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600444 break;
445
446 default:
447 break;
448 }
449
450}
451
452TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
453{
454 if (! mainTerminated) {
455 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
456 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600457 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600458 }
459}
460
461//
462// Implement the traversal functions.
463//
464// Return true from interior nodes to have the external traversal
465// continue on to children. Return false if children were
466// already processed.
467//
468
469//
470// Symbols can turn into
471// - uniform/input reads
472// - output writes
473// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
474// - something simple that degenerates into the last bullet
475//
476void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
477{
478 // getSymbolId() will set up all the IO decorations on the first call.
479 // Formal function parameters were mapped during makeFunctions().
480 spv::Id id = getSymbolId(symbol);
481
482 if (! linkageOnly) {
483 // Prepare to generate code for the access
484
485 // L-value chains will be computed left to right. We're on the symbol now,
486 // which is the left-most part of the access chain, so now is "clear" time,
487 // followed by setting the base.
488 builder.clearAccessChain();
489
490 // For now, we consider all user variables as being in memory, so they are pointers,
491 // except for "const in" arguments to a function, which are an intermediate object.
492 // See comments in handleUserFunctionCall().
493 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
494 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
495 builder.setAccessChainRValue(id);
496 else
497 builder.setAccessChainLValue(id);
498 }
499}
500
501bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
502{
503 // First, handle special cases
504 switch (node->getOp()) {
505 case glslang::EOpAssign:
506 case glslang::EOpAddAssign:
507 case glslang::EOpSubAssign:
508 case glslang::EOpMulAssign:
509 case glslang::EOpVectorTimesMatrixAssign:
510 case glslang::EOpVectorTimesScalarAssign:
511 case glslang::EOpMatrixTimesScalarAssign:
512 case glslang::EOpMatrixTimesMatrixAssign:
513 case glslang::EOpDivAssign:
514 case glslang::EOpModAssign:
515 case glslang::EOpAndAssign:
516 case glslang::EOpInclusiveOrAssign:
517 case glslang::EOpExclusiveOrAssign:
518 case glslang::EOpLeftShiftAssign:
519 case glslang::EOpRightShiftAssign:
520 // A bin-op assign "a += b" means the same thing as "a = a + b"
521 // where a is evaluated before b. For a simple assignment, GLSL
522 // says to evaluate the left before the right. So, always, left
523 // node then right node.
524 {
525 // get the left l-value, save it away
526 builder.clearAccessChain();
527 node->getLeft()->traverse(this);
528 spv::Builder::AccessChain lValue = builder.getAccessChain();
529
530 // evaluate the right
531 builder.clearAccessChain();
532 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600533 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600534
535 if (node->getOp() != glslang::EOpAssign) {
536 // the left is also an r-value
537 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600538 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600539
540 // do the operation
541 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
542 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
543 node->getType().getBasicType());
544
545 // these all need their counterparts in createBinaryOperation()
546 if (rValue == 0)
547 spv::MissingFunctionality("createBinaryOperation");
548 }
549
550 // store the result
551 builder.setAccessChain(lValue);
552 builder.accessChainStore(rValue);
553
554 // assignments are expressions having an rValue after they are evaluated...
555 builder.clearAccessChain();
556 builder.setAccessChainRValue(rValue);
557 }
558 return false;
559 case glslang::EOpIndexDirect:
560 case glslang::EOpIndexDirectStruct:
561 {
562 // Get the left part of the access chain.
563 node->getLeft()->traverse(this);
564
565 // Add the next element in the chain
566
567 int index = 0;
568 if (node->getRight()->getAsConstantUnion() == 0)
569 spv::MissingFunctionality("direct index without a constant node");
570 else
571 index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
572
573 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
574 // This may be, e.g., an anonymous block-member selection, which generally need
575 // index remapping due to hidden members in anonymous blocks.
576 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
577 if (remapper.size() == 0)
578 spv::MissingFunctionality("block without member remapping");
579 else
580 index = remapper[index];
581 }
582
583 if (! node->getLeft()->getType().isArray() &&
584 node->getLeft()->getType().isVector() &&
585 node->getOp() == glslang::EOpIndexDirect) {
586 // This is essentially a hard-coded vector swizzle of size 1,
587 // so short circuit the access-chain stuff with a swizzle.
588 std::vector<unsigned> swizzle;
589 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600590 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600591 } else {
592 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600593 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600594 }
595 }
596 return false;
597 case glslang::EOpIndexIndirect:
598 {
599 // Structure or array or vector indirection.
600 // Will use native SPIR-V access-chain for struct and array indirection;
601 // matrices are arrays of vectors, so will also work for a matrix.
602 // Will use the access chain's 'component' for variable index into a vector.
603
604 // This adapter is building access chains left to right.
605 // Set up the access chain to the left.
606 node->getLeft()->traverse(this);
607
608 // save it so that computing the right side doesn't trash it
609 spv::Builder::AccessChain partial = builder.getAccessChain();
610
611 // compute the next index in the chain
612 builder.clearAccessChain();
613 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600614 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600615
616 // restore the saved access chain
617 builder.setAccessChain(partial);
618
619 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600620 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600621 else
John Kessenichfa668da2015-09-13 14:46:30 -0600622 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600623 }
624 return false;
625 case glslang::EOpVectorSwizzle:
626 {
627 node->getLeft()->traverse(this);
628 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
629 std::vector<unsigned> swizzle;
630 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
631 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600632 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600633 }
634 return false;
635 default:
636 break;
637 }
638
639 // Assume generic binary op...
640
641 // Get the operands
642 builder.clearAccessChain();
643 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600644 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600645
646 builder.clearAccessChain();
647 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600648 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600649
650 spv::Id result;
651 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
652
653 result = createBinaryOperation(node->getOp(), precision,
654 convertGlslangToSpvType(node->getType()), left, right,
655 node->getLeft()->getType().getBasicType());
656
657 if (! result) {
658 spv::MissingFunctionality("glslang binary operation");
659 } else {
660 builder.clearAccessChain();
661 builder.setAccessChainRValue(result);
662
663 return false;
664 }
665
666 return true;
667}
668
669bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
670{
John Kessenichfc51d282015-08-19 13:34:18 -0600671 spv::Id result = spv::NoResult;
672
673 // try texturing first
674 result = createImageTextureFunctionCall(node);
675 if (result != spv::NoResult) {
676 builder.clearAccessChain();
677 builder.setAccessChainRValue(result);
678
679 return false; // done with this node
680 }
681
682 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600683
684 if (node->getOp() == glslang::EOpArrayLength) {
685 // Quite special; won't want to evaluate the operand.
686
687 // Normal .length() would have been constant folded by the front-end.
688 // So, this has to be block.lastMember.length().
689 // SPV wants "block" as the operand, go get it.
690 assert(node->getOperand()->getType().isRuntimeSizedArray());
691 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
692 block->traverse(this);
693 spv::Id length = builder.createUnaryOp(spv::OpArrayLength, builder.makeIntType(32), builder.accessChainGetLValue());
694
695 builder.clearAccessChain();
696 builder.setAccessChainRValue(length);
697
698 return false;
699 }
700
John Kessenichfc51d282015-08-19 13:34:18 -0600701 // Start by evaluating the operand
702
John Kessenich140f3df2015-06-26 16:58:36 -0600703 builder.clearAccessChain();
704 node->getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600705 spv::Id operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600706
707 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
708
709 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600710 if (! result)
711 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600712
713 // if not, then possibly an operation
714 if (! result)
John Kessenichfc51d282015-08-19 13:34:18 -0600715 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand,
716 node->getBasicType() == glslang::EbtFloat || node->getBasicType() == glslang::EbtDouble);
John Kessenich140f3df2015-06-26 16:58:36 -0600717
718 if (result) {
719 builder.clearAccessChain();
720 builder.setAccessChainRValue(result);
721
722 return false; // done with this node
723 }
724
725 // it must be a special case, check...
726 switch (node->getOp()) {
727 case glslang::EOpPostIncrement:
728 case glslang::EOpPostDecrement:
729 case glslang::EOpPreIncrement:
730 case glslang::EOpPreDecrement:
731 {
732 // we need the integer value "1" or the floating point "1.0" to add/subtract
733 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
734 builder.makeFloatConstant(1.0F) :
735 builder.makeIntConstant(1);
736 glslang::TOperator op;
737 if (node->getOp() == glslang::EOpPreIncrement ||
738 node->getOp() == glslang::EOpPostIncrement)
739 op = glslang::EOpAdd;
740 else
741 op = glslang::EOpSub;
742
743 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
744 convertGlslangToSpvType(node->getType()), operand, one,
745 node->getType().getBasicType());
746 if (result == 0)
747 spv::MissingFunctionality("createBinaryOperation for unary");
748
749 // The result of operation is always stored, but conditionally the
750 // consumed result. The consumed result is always an r-value.
751 builder.accessChainStore(result);
752 builder.clearAccessChain();
753 if (node->getOp() == glslang::EOpPreIncrement ||
754 node->getOp() == glslang::EOpPreDecrement)
755 builder.setAccessChainRValue(result);
756 else
757 builder.setAccessChainRValue(operand);
758 }
759
760 return false;
761
762 case glslang::EOpEmitStreamVertex:
763 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
764 return false;
765 case glslang::EOpEndStreamPrimitive:
766 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
767 return false;
768
769 default:
770 spv::MissingFunctionality("glslang unary");
771 break;
772 }
773
774 return true;
775}
776
777bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
778{
John Kessenichfc51d282015-08-19 13:34:18 -0600779 spv::Id result = spv::NoResult;
780
781 // try texturing
782 result = createImageTextureFunctionCall(node);
783 if (result != spv::NoResult) {
784 builder.clearAccessChain();
785 builder.setAccessChainRValue(result);
786
787 return false;
788 }
789
John Kessenich140f3df2015-06-26 16:58:36 -0600790 glslang::TOperator binOp = glslang::EOpNull;
791 bool reduceComparison = true;
792 bool isMatrix = false;
793 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600794 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600795
796 assert(node->getOp());
797
798 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
799
800 switch (node->getOp()) {
801 case glslang::EOpSequence:
802 {
803 if (preVisit)
804 ++sequenceDepth;
805 else
806 --sequenceDepth;
807
808 if (sequenceDepth == 1) {
809 // If this is the parent node of all the functions, we want to see them
810 // early, so all call points have actual SPIR-V functions to reference.
811 // In all cases, still let the traverser visit the children for us.
812 makeFunctions(node->getAsAggregate()->getSequence());
813
814 // Also, we want all globals initializers to go into the entry of main(), before
815 // anything else gets there, so visit out of order, doing them all now.
816 makeGlobalInitializers(node->getAsAggregate()->getSequence());
817
818 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
819 // so do them manually.
820 visitFunctions(node->getAsAggregate()->getSequence());
821
822 return false;
823 }
824
825 return true;
826 }
827 case glslang::EOpLinkerObjects:
828 {
829 if (visit == glslang::EvPreVisit)
830 linkageOnly = true;
831 else
832 linkageOnly = false;
833
834 return true;
835 }
836 case glslang::EOpComma:
837 {
838 // processing from left to right naturally leaves the right-most
839 // lying around in the access chain
840 glslang::TIntermSequence& glslangOperands = node->getSequence();
841 for (int i = 0; i < (int)glslangOperands.size(); ++i)
842 glslangOperands[i]->traverse(this);
843
844 return false;
845 }
846 case glslang::EOpFunction:
847 if (visit == glslang::EvPreVisit) {
848 if (isShaderEntrypoint(node)) {
849 inMain = true;
850 builder.setBuildPoint(shaderEntry->getLastBlock());
851 } else {
852 handleFunctionEntry(node);
853 }
854 } else {
855 if (inMain)
856 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -0600857 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600858 inMain = false;
859 }
860
861 return true;
862 case glslang::EOpParameters:
863 // Parameters will have been consumed by EOpFunction processing, but not
864 // the body, so we still visited the function node's children, making this
865 // child redundant.
866 return false;
867 case glslang::EOpFunctionCall:
868 {
869 if (node->isUserDefined())
870 result = handleUserFunctionCall(node);
John Kessenich140f3df2015-06-26 16:58:36 -0600871
872 if (! result) {
873 spv::MissingFunctionality("glslang function call");
874 glslang::TConstUnionArray emptyConsts;
875 int nextConst = 0;
876 result = createSpvConstant(node->getType(), emptyConsts, nextConst);
877 }
878 builder.clearAccessChain();
879 builder.setAccessChainRValue(result);
880
881 return false;
882 }
883 case glslang::EOpConstructMat2x2:
884 case glslang::EOpConstructMat2x3:
885 case glslang::EOpConstructMat2x4:
886 case glslang::EOpConstructMat3x2:
887 case glslang::EOpConstructMat3x3:
888 case glslang::EOpConstructMat3x4:
889 case glslang::EOpConstructMat4x2:
890 case glslang::EOpConstructMat4x3:
891 case glslang::EOpConstructMat4x4:
892 case glslang::EOpConstructDMat2x2:
893 case glslang::EOpConstructDMat2x3:
894 case glslang::EOpConstructDMat2x4:
895 case glslang::EOpConstructDMat3x2:
896 case glslang::EOpConstructDMat3x3:
897 case glslang::EOpConstructDMat3x4:
898 case glslang::EOpConstructDMat4x2:
899 case glslang::EOpConstructDMat4x3:
900 case glslang::EOpConstructDMat4x4:
901 isMatrix = true;
902 // fall through
903 case glslang::EOpConstructFloat:
904 case glslang::EOpConstructVec2:
905 case glslang::EOpConstructVec3:
906 case glslang::EOpConstructVec4:
907 case glslang::EOpConstructDouble:
908 case glslang::EOpConstructDVec2:
909 case glslang::EOpConstructDVec3:
910 case glslang::EOpConstructDVec4:
911 case glslang::EOpConstructBool:
912 case glslang::EOpConstructBVec2:
913 case glslang::EOpConstructBVec3:
914 case glslang::EOpConstructBVec4:
915 case glslang::EOpConstructInt:
916 case glslang::EOpConstructIVec2:
917 case glslang::EOpConstructIVec3:
918 case glslang::EOpConstructIVec4:
919 case glslang::EOpConstructUint:
920 case glslang::EOpConstructUVec2:
921 case glslang::EOpConstructUVec3:
922 case glslang::EOpConstructUVec4:
923 case glslang::EOpConstructStruct:
924 {
925 std::vector<spv::Id> arguments;
926 translateArguments(node->getSequence(), arguments);
927 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
928 spv::Id constructed;
929 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
930 std::vector<spv::Id> constituents;
931 for (int c = 0; c < (int)arguments.size(); ++c)
932 constituents.push_back(arguments[c]);
933 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
934 } else {
935 if (isMatrix)
936 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
937 else
938 constructed = builder.createConstructor(precision, arguments, resultTypeId);
939 }
940
941 builder.clearAccessChain();
942 builder.setAccessChainRValue(constructed);
943
944 return false;
945 }
946
947 // These six are component-wise compares with component-wise results.
948 // Forward on to createBinaryOperation(), requesting a vector result.
949 case glslang::EOpLessThan:
950 case glslang::EOpGreaterThan:
951 case glslang::EOpLessThanEqual:
952 case glslang::EOpGreaterThanEqual:
953 case glslang::EOpVectorEqual:
954 case glslang::EOpVectorNotEqual:
955 {
956 // Map the operation to a binary
957 binOp = node->getOp();
958 reduceComparison = false;
959 switch (node->getOp()) {
960 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
961 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
962 default: binOp = node->getOp(); break;
963 }
964
965 break;
966 }
967 case glslang::EOpMul:
968 // compontent-wise matrix multiply
969 binOp = glslang::EOpMul;
970 break;
971 case glslang::EOpOuterProduct:
972 // two vectors multiplied to make a matrix
973 binOp = glslang::EOpOuterProduct;
974 break;
975 case glslang::EOpDot:
976 {
977 // for scalar dot product, use multiply
978 glslang::TIntermSequence& glslangOperands = node->getSequence();
979 if (! glslangOperands[0]->getAsTyped()->isVector())
980 binOp = glslang::EOpMul;
981 break;
982 }
983 case glslang::EOpMod:
984 // when an aggregate, this is the floating-point mod built-in function,
985 // which can be emitted by the one in createBinaryOperation()
986 binOp = glslang::EOpMod;
987 break;
John Kessenich140f3df2015-06-26 16:58:36 -0600988 case glslang::EOpEmitVertex:
989 case glslang::EOpEndPrimitive:
990 case glslang::EOpBarrier:
991 case glslang::EOpMemoryBarrier:
992 case glslang::EOpMemoryBarrierAtomicCounter:
993 case glslang::EOpMemoryBarrierBuffer:
994 case glslang::EOpMemoryBarrierImage:
995 case glslang::EOpMemoryBarrierShared:
996 case glslang::EOpGroupMemoryBarrier:
997 noReturnValue = true;
998 // These all have 0 operands and will naturally finish up in the code below for 0 operands
999 break;
1000
John Kessenich426394d2015-07-23 10:22:48 -06001001 case glslang::EOpAtomicAdd:
1002 case glslang::EOpAtomicMin:
1003 case glslang::EOpAtomicMax:
1004 case glslang::EOpAtomicAnd:
1005 case glslang::EOpAtomicOr:
1006 case glslang::EOpAtomicXor:
1007 case glslang::EOpAtomicExchange:
1008 case glslang::EOpAtomicCompSwap:
1009 atomic = true;
1010 break;
1011
John Kessenichfc51d282015-08-19 13:34:18 -06001012 case glslang::EOpAddCarry:
1013 case glslang::EOpSubBorrow:
1014 case glslang::EOpUMulExtended:
1015 case glslang::EOpIMulExtended:
1016 case glslang::EOpBitfieldExtract:
1017 case glslang::EOpBitfieldInsert:
1018 spv::MissingFunctionality("integer aggregate");
1019 break;
1020
1021 case glslang::EOpFma:
John Kessenich78258d32015-08-19 17:30:12 -06001022 case glslang::EOpFrexp:
1023 case glslang::EOpLdexp:
John Kessenichfc51d282015-08-19 13:34:18 -06001024 spv::MissingFunctionality("fma/frexp/ldexp aggregate");
1025 break;
1026
John Kessenich140f3df2015-06-26 16:58:36 -06001027 default:
1028 break;
1029 }
1030
1031 //
1032 // See if it maps to a regular operation.
1033 //
John Kessenich140f3df2015-06-26 16:58:36 -06001034 if (binOp != glslang::EOpNull) {
1035 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1036 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1037 assert(left && right);
1038
1039 builder.clearAccessChain();
1040 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001041 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001042
1043 builder.clearAccessChain();
1044 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001045 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001046
1047 result = createBinaryOperation(binOp, precision,
1048 convertGlslangToSpvType(node->getType()), leftId, rightId,
1049 left->getType().getBasicType(), reduceComparison);
1050
1051 // code above should only make binOp that exists in createBinaryOperation
1052 if (result == 0)
1053 spv::MissingFunctionality("createBinaryOperation for aggregate");
1054
1055 builder.clearAccessChain();
1056 builder.setAccessChainRValue(result);
1057
1058 return false;
1059 }
1060
John Kessenich426394d2015-07-23 10:22:48 -06001061 //
1062 // Create the list of operands.
1063 //
John Kessenich140f3df2015-06-26 16:58:36 -06001064 glslang::TIntermSequence& glslangOperands = node->getSequence();
1065 std::vector<spv::Id> operands;
1066 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1067 builder.clearAccessChain();
1068 glslangOperands[arg]->traverse(this);
1069
1070 // special case l-value operands; there are just a few
1071 bool lvalue = false;
1072 switch (node->getOp()) {
1073 //case glslang::EOpFrexp:
1074 case glslang::EOpModf:
1075 if (arg == 1)
1076 lvalue = true;
1077 break;
1078 //case glslang::EOpUAddCarry:
1079 //case glslang::EOpUSubBorrow:
1080 //case glslang::EOpUMulExtended:
1081 default:
1082 break;
1083 }
1084 if (lvalue)
1085 operands.push_back(builder.accessChainGetLValue());
1086 else
John Kessenichfa668da2015-09-13 14:46:30 -06001087 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001088 }
John Kessenich426394d2015-07-23 10:22:48 -06001089
1090 if (atomic) {
1091 // Handle all atomics
1092 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands);
1093 } else {
1094 // Pass through to generic operations.
1095 switch (glslangOperands.size()) {
1096 case 0:
1097 result = createNoArgOperation(node->getOp());
1098 break;
1099 case 1:
1100 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), node->getType().getBasicType() == glslang::EbtFloat || node->getType().getBasicType() == glslang::EbtDouble);
1101 break;
1102 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001103 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001104 break;
1105 }
John Kessenich140f3df2015-06-26 16:58:36 -06001106 }
1107
1108 if (noReturnValue)
1109 return false;
1110
1111 if (! result) {
1112 spv::MissingFunctionality("glslang aggregate");
1113 return true;
1114 } else {
1115 builder.clearAccessChain();
1116 builder.setAccessChainRValue(result);
1117 return false;
1118 }
1119}
1120
1121bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1122{
1123 // This path handles both if-then-else and ?:
1124 // The if-then-else has a node type of void, while
1125 // ?: has a non-void node type
1126 spv::Id result = 0;
1127 if (node->getBasicType() != glslang::EbtVoid) {
1128 // don't handle this as just on-the-fly temporaries, because there will be two names
1129 // and better to leave SSA to later passes
1130 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1131 }
1132
1133 // emit the condition before doing anything with selection
1134 node->getCondition()->traverse(this);
1135
1136 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001137 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001138
1139 if (node->getTrueBlock()) {
1140 // emit the "then" statement
1141 node->getTrueBlock()->traverse(this);
1142 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001143 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001144 }
1145
1146 if (node->getFalseBlock()) {
1147 ifBuilder.makeBeginElse();
1148 // emit the "else" statement
1149 node->getFalseBlock()->traverse(this);
1150 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001151 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001152 }
1153
1154 ifBuilder.makeEndIf();
1155
1156 if (result) {
1157 // GLSL only has r-values as the result of a :?, but
1158 // if we have an l-value, that can be more efficient if it will
1159 // become the base of a complex r-value expression, because the
1160 // next layer copies r-values into memory to use the access-chain mechanism
1161 builder.clearAccessChain();
1162 builder.setAccessChainLValue(result);
1163 }
1164
1165 return false;
1166}
1167
1168bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1169{
1170 // emit and get the condition before doing anything with switch
1171 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001172 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001173
1174 // browse the children to sort out code segments
1175 int defaultSegment = -1;
1176 std::vector<TIntermNode*> codeSegments;
1177 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1178 std::vector<int> caseValues;
1179 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1180 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1181 TIntermNode* child = *c;
1182 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001183 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001184 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001185 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001186 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1187 } else
1188 codeSegments.push_back(child);
1189 }
1190
1191 // handle the case where the last code segment is missing, due to no code
1192 // statements between the last case and the end of the switch statement
1193 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1194 (int)codeSegments.size() == defaultSegment)
1195 codeSegments.push_back(nullptr);
1196
1197 // make the switch statement
1198 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001199 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001200
1201 // emit all the code in the segments
1202 breakForLoop.push(false);
1203 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1204 builder.nextSwitchSegment(segmentBlocks, s);
1205 if (codeSegments[s])
1206 codeSegments[s]->traverse(this);
1207 else
1208 builder.addSwitchBreak();
1209 }
1210 breakForLoop.pop();
1211
1212 builder.endSwitch(segmentBlocks);
1213
1214 return false;
1215}
1216
1217void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1218{
1219 int nextConst = 0;
1220 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1221
1222 builder.clearAccessChain();
1223 builder.setAccessChainRValue(constant);
1224}
1225
1226bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1227{
1228 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1229 loopTerminal.push(node->getTerminal());
1230
David Netoc22f37c2015-07-15 16:21:26 -04001231 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001232
1233 if (node->getTest()) {
1234 node->getTest()->traverse(this);
1235 // the AST only contained the test computation, not the branch, we have to add it
John Kessenichfa668da2015-09-13 14:46:30 -06001236 spv::Id condition = builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001237 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001238 } else {
1239 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001240 }
1241
David Netoc22f37c2015-07-15 16:21:26 -04001242 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001243 breakForLoop.push(true);
1244 node->getBody()->traverse(this);
1245 breakForLoop.pop();
1246 }
1247
1248 if (loopTerminal.top())
1249 loopTerminal.top()->traverse(this);
1250
1251 builder.closeLoop();
1252
1253 loopTerminal.pop();
1254
1255 return false;
1256}
1257
1258bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1259{
1260 if (node->getExpression())
1261 node->getExpression()->traverse(this);
1262
1263 switch (node->getFlowOp()) {
1264 case glslang::EOpKill:
1265 builder.makeDiscard();
1266 break;
1267 case glslang::EOpBreak:
1268 if (breakForLoop.top())
1269 builder.createLoopExit();
1270 else
1271 builder.addSwitchBreak();
1272 break;
1273 case glslang::EOpContinue:
1274 if (loopTerminal.top())
1275 loopTerminal.top()->traverse(this);
1276 builder.createLoopContinue();
1277 break;
1278 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001279 if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001280 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001281 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001282 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001283
1284 builder.clearAccessChain();
1285 break;
1286
1287 default:
1288 spv::MissingFunctionality("branch type");
1289 break;
1290 }
1291
1292 return false;
1293}
1294
1295spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1296{
1297 // First, steer off constants, which are not SPIR-V variables, but
1298 // can still have a mapping to a SPIR-V Id.
1299 if (node->getQualifier().storage == glslang::EvqConst) {
1300 int nextConst = 0;
1301 return createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1302 }
1303
1304 // Now, handle actual variables
1305 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1306 spv::Id spvType = convertGlslangToSpvType(node->getType());
1307
1308 const char* name = node->getName().c_str();
1309 if (glslang::IsAnonymous(name))
1310 name = "";
1311
1312 return builder.createVariable(storageClass, spvType, name);
1313}
1314
1315// Return type Id of the sampled type.
1316spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1317{
1318 switch (sampler.type) {
1319 case glslang::EbtFloat: return builder.makeFloatType(32);
1320 case glslang::EbtInt: return builder.makeIntType(32);
1321 case glslang::EbtUint: return builder.makeUintType(32);
1322 default:
1323 spv::MissingFunctionality("sampled type");
1324 return builder.makeFloatType(32);
1325 }
1326}
1327
John Kessenich31ed4832015-09-09 17:51:38 -06001328// Convert from a glslang type to an SPV type, by calling into
1329// recursive version of this function.
John Kessenich140f3df2015-06-26 16:58:36 -06001330spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1331{
John Kessenich31ed4832015-09-09 17:51:38 -06001332 return convertGlslangToSpvType(type, requiresExplicitLayout(type));
1333}
1334
1335// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1336// explicitLayout can be kept the same throughout the heirarchical recursive walk.
1337spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout)
1338{
John Kessenich140f3df2015-06-26 16:58:36 -06001339 spv::Id spvType = 0;
1340
1341 switch (type.getBasicType()) {
1342 case glslang::EbtVoid:
1343 spvType = builder.makeVoidType();
1344 if (type.isArray())
1345 spv::MissingFunctionality("array of void");
1346 break;
1347 case glslang::EbtFloat:
1348 spvType = builder.makeFloatType(32);
1349 break;
1350 case glslang::EbtDouble:
1351 spvType = builder.makeFloatType(64);
1352 break;
1353 case glslang::EbtBool:
1354 spvType = builder.makeBoolType();
1355 break;
1356 case glslang::EbtInt:
1357 spvType = builder.makeIntType(32);
1358 break;
1359 case glslang::EbtUint:
1360 spvType = builder.makeUintType(32);
1361 break;
John Kessenich426394d2015-07-23 10:22:48 -06001362 case glslang::EbtAtomicUint:
1363 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1364 spvType = builder.makeUintType(32);
1365 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001366 case glslang::EbtSampler:
1367 {
1368 const glslang::TSampler& sampler = type.getSampler();
John Kessenich5e4b1242015-08-06 22:53:06 -06001369 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1370 sampler.image ? 2 : 1, spv::ImageFormatUnknown); // TODO: translate format, needed for GLSL image ops
1371 // OpenGL "textures" need to be combined with a sampler
1372 if (! sampler.image)
1373 spvType = builder.makeSampledImageType(spvType);
John Kessenich140f3df2015-06-26 16:58:36 -06001374 }
1375 break;
1376 case glslang::EbtStruct:
1377 case glslang::EbtBlock:
1378 {
1379 // If we've seen this struct type, return it
1380 const glslang::TTypeList* glslangStruct = type.getStruct();
1381 std::vector<spv::Id> structFields;
1382 spvType = structMap[glslangStruct];
1383 if (spvType)
1384 break;
1385
1386 // else, we haven't seen it...
1387
1388 // Create a vector of struct types for SPIR-V to consume
1389 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1390 if (type.getBasicType() == glslang::EbtBlock)
1391 memberRemapper[glslangStruct].resize(glslangStruct->size());
1392 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1393 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1394 if (glslangType.hiddenMember()) {
1395 ++memberDelta;
1396 if (type.getBasicType() == glslang::EbtBlock)
1397 memberRemapper[glslangStruct][i] = -1;
1398 } else {
1399 if (type.getBasicType() == glslang::EbtBlock)
1400 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kessenich31ed4832015-09-09 17:51:38 -06001401 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001402 }
1403 }
1404
1405 // Make the SPIR-V type
1406 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
1407 structMap[glslangStruct] = spvType;
1408
1409 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001410 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001411 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1412 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1413 int member = i;
1414 if (type.getBasicType() == glslang::EbtBlock)
1415 member = memberRemapper[glslangStruct][i];
1416 // using -1 above to indicate a hidden member
1417 if (member >= 0) {
1418 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
1419 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType));
1420 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1421 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1422 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1423 if (glslangType.getQualifier().hasLocation())
1424 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1425 if (glslangType.getQualifier().hasComponent())
1426 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1427 if (glslangType.getQualifier().hasXfbOffset())
1428 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenich31ed4832015-09-09 17:51:38 -06001429 else if (explicitLayout) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001430 // figure out what to do with offset, which is accumulating
1431 int nextOffset;
1432 updateMemberOffset(type, glslangType, offset, nextOffset);
1433 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001434 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001435 offset = nextOffset;
1436 }
John Kessenich140f3df2015-06-26 16:58:36 -06001437
John Kessenich31ed4832015-09-09 17:51:38 -06001438 if (glslangType.isMatrix() && explicitLayout) {
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001439 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType));
1440 }
1441
John Kessenich140f3df2015-06-26 16:58:36 -06001442 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001443 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1444 if (builtIn != spv::BadValue)
1445 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001446 }
1447 }
1448
1449 // Decorate the structure
1450 addDecoration(spvType, TranslateLayoutDecoration(type));
1451 addDecoration(spvType, TranslateBlockDecoration(type));
1452 if (type.getQualifier().hasStream())
1453 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1454 if (glslangIntermediate->getXfbMode()) {
1455 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001456 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001457 if (type.getQualifier().hasXfbBuffer())
1458 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1459 }
1460 }
1461 break;
1462 default:
1463 spv::MissingFunctionality("basic type");
1464 break;
1465 }
1466
1467 if (type.isMatrix())
1468 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1469 else {
1470 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1471 if (type.getVectorSize() > 1)
1472 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1473 }
1474
1475 if (type.isArray()) {
John Kessenichc9a80832015-09-12 12:17:44 -06001476 // Do all but the outer dimension
1477 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1478 assert(type.getArraySizes()->getDimSize(dim) > 0);
1479 spvType = builder.makeArrayType(spvType, type.getArraySizes()->getDimSize(dim));
1480 }
John Kessenich31ed4832015-09-09 17:51:38 -06001481
John Kessenichc9a80832015-09-12 12:17:44 -06001482 // Do the outer dimension, which might not be known for a runtime-sized array
1483 if (type.isRuntimeSizedArray()) {
1484 spvType = builder.makeRuntimeArray(spvType);
1485 } else {
1486 assert(type.getOuterArraySize() > 0);
1487 spvType = builder.makeArrayType(spvType, type.getOuterArraySize());
1488 }
1489
1490 // TODO: layout still needs to be done hierarchically for arrays of arrays, which
1491 // may still require additional "link time" support from the front-end
1492 // for arrays of arrays
John Kessenich31ed4832015-09-09 17:51:38 -06001493 if (explicitLayout)
1494 builder.addDecoration(spvType, spv::DecorationArrayStride, getArrayStride(type));
John Kessenich140f3df2015-06-26 16:58:36 -06001495 }
1496
1497 return spvType;
1498}
1499
John Kessenich31ed4832015-09-09 17:51:38 -06001500bool TGlslangToSpvTraverser::requiresExplicitLayout(const glslang::TType& type) const
1501{
1502 return type.getBasicType() == glslang::EbtBlock &&
1503 type.getQualifier().layoutPacking != glslang::ElpShared &&
1504 type.getQualifier().layoutPacking != glslang::ElpPacked &&
1505 (type.getQualifier().storage == glslang::EvqUniform ||
1506 type.getQualifier().storage == glslang::EvqBuffer);
1507}
1508
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001509// Given an array type, returns the integer stride required for that array
1510int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType)
1511{
1512 glslang::TType derefType(arrayType, 0);
1513 int size;
1514 glslangIntermediate->getBaseAlignment(derefType, size, true);
1515 return size;
1516}
1517
1518// Given a matrix type, returns the integer stride required for that matrix
1519// when used as a member of an interface block
1520int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType)
1521{
1522 int size;
1523 return glslangIntermediate->getBaseAlignment(matrixType, size, true);
1524}
1525
John Kessenich5e4b1242015-08-06 22:53:06 -06001526// Given a member type of a struct, realign the current offset for it, and compute
1527// the next (not yet aligned) offset for the next member, which will get aligned
1528// on the next call.
1529// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1530// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1531// -1 means a non-forced member offset (no decoration needed).
1532void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset)
1533{
1534 // this will get a positive value when deemed necessary
1535 nextOffset = -1;
1536
1537 bool forceOffset = structType.getQualifier().layoutPacking == glslang::ElpStd140 ||
1538 structType.getQualifier().layoutPacking == glslang::ElpStd430;
1539
1540 // override anything in currentOffset with user-set offset
1541 if (memberType.getQualifier().hasOffset())
1542 currentOffset = memberType.getQualifier().layoutOffset;
1543
1544 // It could be that current linker usage in glslang updated all the layoutOffset,
1545 // in which case the following code does not matter. But, that's not quite right
1546 // once cross-compilation unit GLSL validation is done, as the original user
1547 // settings are needed in layoutOffset, and then the following will come into play.
1548
1549 if (! forceOffset) {
1550 if (! memberType.getQualifier().hasOffset())
1551 currentOffset = -1;
1552
1553 return;
1554 }
1555
1556 // Getting this far means we are forcing offsets
1557 if (currentOffset < 0)
1558 currentOffset = 0;
1559
1560 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1561 // but possibly not yet correctly aligned.
1562
1563 int memberSize;
1564 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, memberType.getQualifier().layoutPacking == glslang::ElpStd140);
1565 glslang::RoundToPow2(currentOffset, memberAlignment);
1566 nextOffset = currentOffset + memberSize;
1567}
1568
John Kessenich140f3df2015-06-26 16:58:36 -06001569bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1570{
1571 return node->getName() == "main(";
1572}
1573
1574// Make all the functions, skeletally, without actually visiting their bodies.
1575void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1576{
1577 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1578 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1579 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1580 continue;
1581
1582 // We're on a user function. Set up the basic interface for the function now,
1583 // so that it's available to call.
1584 // Translating the body will happen later.
1585 //
1586 // Typically (except for a "const in" parameter), an address will be passed to the
1587 // function. What it is an address of varies:
1588 //
1589 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1590 // so that write needs to be to a copy, hence the address of a copy works.
1591 //
1592 // - "const in" parameters can just be the r-value, as no writes need occur.
1593 //
1594 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1595 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1596
1597 std::vector<spv::Id> paramTypes;
1598 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1599
1600 for (int p = 0; p < (int)parameters.size(); ++p) {
1601 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1602 spv::Id typeId = convertGlslangToSpvType(paramType);
1603 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1604 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1605 else
1606 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1607 paramTypes.push_back(typeId);
1608 }
1609
1610 spv::Block* functionBlock;
1611 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1612 paramTypes, &functionBlock);
1613
1614 // Track function to emit/call later
1615 functionMap[glslFunction->getName().c_str()] = function;
1616
1617 // Set the parameter id's
1618 for (int p = 0; p < (int)parameters.size(); ++p) {
1619 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1620 // give a name too
1621 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1622 }
1623 }
1624}
1625
1626// Process all the initializers, while skipping the functions and link objects
1627void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1628{
1629 builder.setBuildPoint(shaderEntry->getLastBlock());
1630 for (int i = 0; i < (int)initializers.size(); ++i) {
1631 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1632 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1633
1634 // We're on a top-level node that's not a function. Treat as an initializer, whose
1635 // code goes into the beginning of main.
1636 initializer->traverse(this);
1637 }
1638 }
1639}
1640
1641// Process all the functions, while skipping initializers.
1642void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1643{
1644 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1645 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1646 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1647 node->traverse(this);
1648 }
1649}
1650
1651void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1652{
1653 // SPIR-V functions should already be in the functionMap from the prepass
1654 // that called makeFunctions().
1655 spv::Function* function = functionMap[node->getName().c_str()];
1656 spv::Block* functionBlock = function->getEntryBlock();
1657 builder.setBuildPoint(functionBlock);
1658}
1659
1660void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermSequence& glslangArguments, std::vector<spv::Id>& arguments)
1661{
1662 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1663 builder.clearAccessChain();
1664 glslangArguments[i]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001665 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001666 }
1667}
1668
John Kessenichfc51d282015-08-19 13:34:18 -06001669void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001670{
John Kessenichfc51d282015-08-19 13:34:18 -06001671 builder.clearAccessChain();
1672 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001673 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06001674}
John Kessenich140f3df2015-06-26 16:58:36 -06001675
John Kessenichfc51d282015-08-19 13:34:18 -06001676spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1677{
1678 if (node->isImage()) {
1679 spv::MissingFunctionality("GLSL image function");
1680 return spv::NoResult;
1681 } else if (! node->isTexture()) {
1682 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001683 }
1684
John Kessenichfc51d282015-08-19 13:34:18 -06001685 // Process a GLSL texturing op (will be SPV image)
John Kessenich140f3df2015-06-26 16:58:36 -06001686
John Kessenichfc51d282015-08-19 13:34:18 -06001687 glslang::TCrackedTextureOp cracked;
1688 node->crackTexture(cracked);
1689
1690 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1691 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1692 std::vector<spv::Id> arguments;
1693 if (node->getAsAggregate())
1694 translateArguments(node->getAsAggregate()->getSequence(), arguments);
1695 else
1696 translateArguments(*node->getAsUnaryNode(), arguments);
1697 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1698
1699 spv::Builder::TextureParameters params = { };
1700 params.sampler = arguments[0];
1701
1702 // Check for queries
1703 if (cracked.query) {
1704 switch (node->getOp()) {
1705 case glslang::EOpImageQuerySize:
1706 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001707 if (arguments.size() > 1) {
1708 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001709 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001710 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001711 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001712 case glslang::EOpImageQuerySamples:
1713 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001714 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001715 case glslang::EOpTextureQueryLod:
1716 params.coords = arguments[1];
1717 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1718 case glslang::EOpTextureQueryLevels:
1719 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1720 default:
1721 assert(0);
1722 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001723 }
John Kessenich140f3df2015-06-26 16:58:36 -06001724 }
1725
John Kessenichfc51d282015-08-19 13:34:18 -06001726 // This is no longer a query....
John Kessenich140f3df2015-06-26 16:58:36 -06001727
John Kessenichfc51d282015-08-19 13:34:18 -06001728 if (cracked.gather)
1729 spv::MissingFunctionality("texture gather");
1730
1731 // check for bias argument
1732 bool bias = false;
1733 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch) {
1734 int nonBiasArgCount = 2;
1735 if (cracked.offset)
1736 ++nonBiasArgCount;
1737 if (cracked.grad)
1738 nonBiasArgCount += 2;
1739
1740 if ((int)arguments.size() > nonBiasArgCount)
1741 bias = true;
1742 }
1743
1744 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1745
1746 // set the rest of the arguments
1747 params.coords = arguments[1];
1748 int extraArgs = 0;
1749 if (cubeCompare)
1750 params.Dref = arguments[2];
1751 else if (sampler.shadow) {
1752 std::vector<spv::Id> indexes;
1753 int comp;
1754 if (cracked.proj)
1755 comp = 3;
1756 else
1757 comp = builder.getNumComponents(params.coords) - 1;
1758 indexes.push_back(comp);
1759 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1760 }
1761 if (cracked.lod) {
1762 params.lod = arguments[2];
1763 ++extraArgs;
1764 }
1765 if (cracked.grad) {
1766 params.gradX = arguments[2 + extraArgs];
1767 params.gradY = arguments[3 + extraArgs];
1768 extraArgs += 2;
1769 }
1770 //if (gather && compare) {
1771 // params.compare = arguments[2 + extraArgs];
1772 // ++extraArgs;
1773 //}
1774 if (cracked.offset || cracked.offsets) {
1775 params.offset = arguments[2 + extraArgs];
1776 ++extraArgs;
1777 }
1778 if (bias) {
1779 params.bias = arguments[2 + extraArgs];
1780 ++extraArgs;
1781 }
1782
Jason Ekstrand18b9fbd2015-09-05 14:14:48 -07001783 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001784}
1785
1786spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
1787{
1788 // Grab the function's pointer from the previously created function
1789 spv::Function* function = functionMap[node->getName().c_str()];
1790 if (! function)
1791 return 0;
1792
1793 const glslang::TIntermSequence& glslangArgs = node->getSequence();
1794 const glslang::TQualifierList& qualifiers = node->getQualifierList();
1795
1796 // See comments in makeFunctions() for details about the semantics for parameter passing.
1797 //
1798 // These imply we need a four step process:
1799 // 1. Evaluate the arguments
1800 // 2. Allocate and make copies of in, out, and inout arguments
1801 // 3. Make the call
1802 // 4. Copy back the results
1803
1804 // 1. Evaluate the arguments
1805 std::vector<spv::Builder::AccessChain> lValues;
1806 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06001807 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06001808 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1809 // build l-value
1810 builder.clearAccessChain();
1811 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001812 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001813 // keep outputs as l-values, evaluate input-only as r-values
1814 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1815 // save l-value
1816 lValues.push_back(builder.getAccessChain());
1817 } else {
1818 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06001819 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06001820 }
1821 }
1822
1823 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
1824 // copy the original into that space.
1825 //
1826 // Also, build up the list of actual arguments to pass in for the call
1827 int lValueCount = 0;
1828 int rValueCount = 0;
1829 std::vector<spv::Id> spvArgs;
1830 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1831 spv::Id arg;
1832 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1833 // need space to hold the copy
1834 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
1835 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
1836 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
1837 // need to copy the input into output space
1838 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06001839 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06001840 builder.createStore(copy, arg);
1841 }
1842 ++lValueCount;
1843 } else {
1844 arg = rValues[rValueCount];
1845 ++rValueCount;
1846 }
1847 spvArgs.push_back(arg);
1848 }
1849
1850 // 3. Make the call.
1851 spv::Id result = builder.createFunctionCall(function, spvArgs);
1852
1853 // 4. Copy back out an "out" arguments.
1854 lValueCount = 0;
1855 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1856 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1857 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
1858 spv::Id copy = builder.createLoad(spvArgs[a]);
1859 builder.setAccessChain(lValues[lValueCount]);
1860 builder.accessChainStore(copy);
1861 }
1862 ++lValueCount;
1863 }
1864 }
1865
1866 return result;
1867}
1868
1869// Translate AST operation to SPV operation, already having SPV-based operands/types.
1870spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
1871 spv::Id typeId, spv::Id left, spv::Id right,
1872 glslang::TBasicType typeProxy, bool reduceComparison)
1873{
1874 bool isUnsigned = typeProxy == glslang::EbtUint;
1875 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
1876
1877 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06001878 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06001879 bool comparison = false;
1880
1881 switch (op) {
1882 case glslang::EOpAdd:
1883 case glslang::EOpAddAssign:
1884 if (isFloat)
1885 binOp = spv::OpFAdd;
1886 else
1887 binOp = spv::OpIAdd;
1888 break;
1889 case glslang::EOpSub:
1890 case glslang::EOpSubAssign:
1891 if (isFloat)
1892 binOp = spv::OpFSub;
1893 else
1894 binOp = spv::OpISub;
1895 break;
1896 case glslang::EOpMul:
1897 case glslang::EOpMulAssign:
1898 if (isFloat)
1899 binOp = spv::OpFMul;
1900 else
1901 binOp = spv::OpIMul;
1902 break;
1903 case glslang::EOpVectorTimesScalar:
1904 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06001905 if (isFloat) {
1906 if (builder.isVector(right))
1907 std::swap(left, right);
1908 assert(builder.isScalar(right));
1909 needMatchingVectors = false;
1910 binOp = spv::OpVectorTimesScalar;
1911 } else
1912 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06001913 break;
1914 case glslang::EOpVectorTimesMatrix:
1915 case glslang::EOpVectorTimesMatrixAssign:
1916 assert(builder.isVector(left));
1917 assert(builder.isMatrix(right));
1918 binOp = spv::OpVectorTimesMatrix;
1919 break;
1920 case glslang::EOpMatrixTimesVector:
1921 assert(builder.isMatrix(left));
1922 assert(builder.isVector(right));
1923 binOp = spv::OpMatrixTimesVector;
1924 break;
1925 case glslang::EOpMatrixTimesScalar:
1926 case glslang::EOpMatrixTimesScalarAssign:
1927 if (builder.isMatrix(right))
1928 std::swap(left, right);
1929 assert(builder.isScalar(right));
1930 binOp = spv::OpMatrixTimesScalar;
1931 break;
1932 case glslang::EOpMatrixTimesMatrix:
1933 case glslang::EOpMatrixTimesMatrixAssign:
1934 assert(builder.isMatrix(left));
1935 assert(builder.isMatrix(right));
1936 binOp = spv::OpMatrixTimesMatrix;
1937 break;
1938 case glslang::EOpOuterProduct:
1939 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06001940 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001941 break;
1942
1943 case glslang::EOpDiv:
1944 case glslang::EOpDivAssign:
1945 if (isFloat)
1946 binOp = spv::OpFDiv;
1947 else if (isUnsigned)
1948 binOp = spv::OpUDiv;
1949 else
1950 binOp = spv::OpSDiv;
1951 break;
1952 case glslang::EOpMod:
1953 case glslang::EOpModAssign:
1954 if (isFloat)
1955 binOp = spv::OpFMod;
1956 else if (isUnsigned)
1957 binOp = spv::OpUMod;
1958 else
1959 binOp = spv::OpSMod;
1960 break;
1961 case glslang::EOpRightShift:
1962 case glslang::EOpRightShiftAssign:
1963 if (isUnsigned)
1964 binOp = spv::OpShiftRightLogical;
1965 else
1966 binOp = spv::OpShiftRightArithmetic;
1967 break;
1968 case glslang::EOpLeftShift:
1969 case glslang::EOpLeftShiftAssign:
1970 binOp = spv::OpShiftLeftLogical;
1971 break;
1972 case glslang::EOpAnd:
1973 case glslang::EOpAndAssign:
1974 binOp = spv::OpBitwiseAnd;
1975 break;
1976 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06001977 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001978 binOp = spv::OpLogicalAnd;
1979 break;
1980 case glslang::EOpInclusiveOr:
1981 case glslang::EOpInclusiveOrAssign:
1982 binOp = spv::OpBitwiseOr;
1983 break;
1984 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06001985 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001986 binOp = spv::OpLogicalOr;
1987 break;
1988 case glslang::EOpExclusiveOr:
1989 case glslang::EOpExclusiveOrAssign:
1990 binOp = spv::OpBitwiseXor;
1991 break;
1992 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06001993 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06001994 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06001995 break;
1996
1997 case glslang::EOpLessThan:
1998 case glslang::EOpGreaterThan:
1999 case glslang::EOpLessThanEqual:
2000 case glslang::EOpGreaterThanEqual:
2001 case glslang::EOpEqual:
2002 case glslang::EOpNotEqual:
2003 case glslang::EOpVectorEqual:
2004 case glslang::EOpVectorNotEqual:
2005 comparison = true;
2006 break;
2007 default:
2008 break;
2009 }
2010
2011 if (binOp != spv::OpNop) {
2012 if (builder.isMatrix(left) || builder.isMatrix(right)) {
2013 switch (binOp) {
2014 case spv::OpMatrixTimesScalar:
2015 case spv::OpVectorTimesMatrix:
2016 case spv::OpMatrixTimesVector:
2017 case spv::OpMatrixTimesMatrix:
2018 break;
2019 case spv::OpFDiv:
2020 // turn it into a multiply...
2021 assert(builder.isMatrix(left) && builder.isScalar(right));
2022 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2023 binOp = spv::OpFMul;
2024 break;
2025 default:
2026 spv::MissingFunctionality("binary operation on matrix");
2027 break;
2028 }
2029
2030 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2031 builder.setPrecision(id, precision);
2032
2033 return id;
2034 }
2035
2036 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002037 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002038 builder.promoteScalar(precision, left, right);
2039
2040 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2041 builder.setPrecision(id, precision);
2042
2043 return id;
2044 }
2045
2046 if (! comparison)
2047 return 0;
2048
2049 // Comparison instructions
2050
2051 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2052 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2053
2054 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
2055 }
2056
2057 switch (op) {
2058 case glslang::EOpLessThan:
2059 if (isFloat)
2060 binOp = spv::OpFOrdLessThan;
2061 else if (isUnsigned)
2062 binOp = spv::OpULessThan;
2063 else
2064 binOp = spv::OpSLessThan;
2065 break;
2066 case glslang::EOpGreaterThan:
2067 if (isFloat)
2068 binOp = spv::OpFOrdGreaterThan;
2069 else if (isUnsigned)
2070 binOp = spv::OpUGreaterThan;
2071 else
2072 binOp = spv::OpSGreaterThan;
2073 break;
2074 case glslang::EOpLessThanEqual:
2075 if (isFloat)
2076 binOp = spv::OpFOrdLessThanEqual;
2077 else if (isUnsigned)
2078 binOp = spv::OpULessThanEqual;
2079 else
2080 binOp = spv::OpSLessThanEqual;
2081 break;
2082 case glslang::EOpGreaterThanEqual:
2083 if (isFloat)
2084 binOp = spv::OpFOrdGreaterThanEqual;
2085 else if (isUnsigned)
2086 binOp = spv::OpUGreaterThanEqual;
2087 else
2088 binOp = spv::OpSGreaterThanEqual;
2089 break;
2090 case glslang::EOpEqual:
2091 case glslang::EOpVectorEqual:
2092 if (isFloat)
2093 binOp = spv::OpFOrdEqual;
2094 else
2095 binOp = spv::OpIEqual;
2096 break;
2097 case glslang::EOpNotEqual:
2098 case glslang::EOpVectorNotEqual:
2099 if (isFloat)
2100 binOp = spv::OpFOrdNotEqual;
2101 else
2102 binOp = spv::OpINotEqual;
2103 break;
2104 default:
2105 break;
2106 }
2107
2108 if (binOp != spv::OpNop) {
2109 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2110 builder.setPrecision(id, precision);
2111
2112 return id;
2113 }
2114
2115 return 0;
2116}
2117
2118spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, bool isFloat)
2119{
2120 spv::Op unaryOp = spv::OpNop;
2121 int libCall = -1;
2122
2123 switch (op) {
2124 case glslang::EOpNegative:
2125 if (isFloat)
2126 unaryOp = spv::OpFNegate;
2127 else
2128 unaryOp = spv::OpSNegate;
2129 break;
2130
2131 case glslang::EOpLogicalNot:
2132 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002133 unaryOp = spv::OpLogicalNot;
2134 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002135 case glslang::EOpBitwiseNot:
2136 unaryOp = spv::OpNot;
2137 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002138
John Kessenich140f3df2015-06-26 16:58:36 -06002139 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002140 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002141 break;
2142 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002143 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002144 break;
2145 case glslang::EOpTranspose:
2146 unaryOp = spv::OpTranspose;
2147 break;
2148
2149 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002150 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002151 break;
2152 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002153 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002154 break;
2155 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002156 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002157 break;
2158 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002159 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002160 break;
2161 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002162 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002163 break;
2164 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002165 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002166 break;
2167 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002168 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002169 break;
2170 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002171 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002172 break;
2173
2174 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002175 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002176 break;
2177 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002178 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002179 break;
2180 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002181 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002182 break;
2183 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002184 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002185 break;
2186 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002187 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002188 break;
2189 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002190 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002191 break;
2192
2193 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002194 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002195 break;
2196 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002197 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002198 break;
2199
2200 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002201 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002202 break;
2203 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002204 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002205 break;
2206 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002207 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002208 break;
2209 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002210 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002211 break;
2212 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002213 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002214 break;
2215 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002216 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002217 break;
2218
2219 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002220 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002221 break;
2222 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002223 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002224 break;
2225 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002226 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002227 break;
2228 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002229 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002230 break;
2231 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002232 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002233 break;
2234 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002235 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002236 break;
2237
2238 case glslang::EOpIsNan:
2239 unaryOp = spv::OpIsNan;
2240 break;
2241 case glslang::EOpIsInf:
2242 unaryOp = spv::OpIsInf;
2243 break;
2244
John Kessenich140f3df2015-06-26 16:58:36 -06002245 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002246 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002247 break;
2248 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002249 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002250 break;
2251 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002252 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002253 break;
2254 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002255 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002256 break;
2257 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002258 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002259 break;
2260 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002261 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002262 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002263 case glslang::EOpPackSnorm4x8:
2264 libCall = spv::GLSLstd450PackSnorm4x8;
2265 break;
2266 case glslang::EOpUnpackSnorm4x8:
2267 libCall = spv::GLSLstd450UnpackSnorm4x8;
2268 break;
2269 case glslang::EOpPackUnorm4x8:
2270 libCall = spv::GLSLstd450PackUnorm4x8;
2271 break;
2272 case glslang::EOpUnpackUnorm4x8:
2273 libCall = spv::GLSLstd450UnpackUnorm4x8;
2274 break;
2275 case glslang::EOpPackDouble2x32:
2276 libCall = spv::GLSLstd450PackDouble2x32;
2277 break;
2278 case glslang::EOpUnpackDouble2x32:
2279 libCall = spv::GLSLstd450UnpackDouble2x32;
2280 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002281
2282 case glslang::EOpDPdx:
2283 unaryOp = spv::OpDPdx;
2284 break;
2285 case glslang::EOpDPdy:
2286 unaryOp = spv::OpDPdy;
2287 break;
2288 case glslang::EOpFwidth:
2289 unaryOp = spv::OpFwidth;
2290 break;
2291 case glslang::EOpDPdxFine:
2292 unaryOp = spv::OpDPdxFine;
2293 break;
2294 case glslang::EOpDPdyFine:
2295 unaryOp = spv::OpDPdyFine;
2296 break;
2297 case glslang::EOpFwidthFine:
2298 unaryOp = spv::OpFwidthFine;
2299 break;
2300 case glslang::EOpDPdxCoarse:
2301 unaryOp = spv::OpDPdxCoarse;
2302 break;
2303 case glslang::EOpDPdyCoarse:
2304 unaryOp = spv::OpDPdyCoarse;
2305 break;
2306 case glslang::EOpFwidthCoarse:
2307 unaryOp = spv::OpFwidthCoarse;
2308 break;
2309
2310 case glslang::EOpAny:
2311 unaryOp = spv::OpAny;
2312 break;
2313 case glslang::EOpAll:
2314 unaryOp = spv::OpAll;
2315 break;
2316
2317 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002318 if (isFloat)
2319 libCall = spv::GLSLstd450FAbs;
2320 else
2321 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002322 break;
2323 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002324 if (isFloat)
2325 libCall = spv::GLSLstd450FSign;
2326 else
2327 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002328 break;
2329
John Kessenichfc51d282015-08-19 13:34:18 -06002330 case glslang::EOpAtomicCounterIncrement:
2331 case glslang::EOpAtomicCounterDecrement:
2332 case glslang::EOpAtomicCounter:
2333 {
2334 // Handle all of the atomics in one place, in createAtomicOperation()
2335 std::vector<spv::Id> operands;
2336 operands.push_back(operand);
2337 return createAtomicOperation(op, precision, typeId, operands);
2338 }
2339
2340 case glslang::EOpImageLoad:
2341 unaryOp = spv::OpImageRead;
2342 break;
2343
2344 case glslang::EOpBitFieldReverse:
2345 unaryOp = spv::OpBitReverse;
2346 break;
2347 case glslang::EOpBitCount:
2348 unaryOp = spv::OpBitCount;
2349 break;
2350 case glslang::EOpFindLSB:
2351 libCall = spv::GLSLstd450FindILSB;
2352 break;
2353 case glslang::EOpFindMSB:
2354 spv::MissingFunctionality("signed vs. unsigned FindMSB");
2355 libCall = spv::GLSLstd450FindSMSB;
2356 break;
2357
John Kessenich140f3df2015-06-26 16:58:36 -06002358 default:
2359 return 0;
2360 }
2361
2362 spv::Id id;
2363 if (libCall >= 0) {
2364 std::vector<spv::Id> args;
2365 args.push_back(operand);
2366 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2367 } else
2368 id = builder.createUnaryOp(unaryOp, typeId, operand);
2369
2370 builder.setPrecision(id, precision);
2371
2372 return id;
2373}
2374
2375spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2376{
2377 spv::Op convOp = spv::OpNop;
2378 spv::Id zero = 0;
2379 spv::Id one = 0;
2380
2381 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2382
2383 switch (op) {
2384 case glslang::EOpConvIntToBool:
2385 case glslang::EOpConvUintToBool:
2386 zero = builder.makeUintConstant(0);
2387 zero = makeSmearedConstant(zero, vectorSize);
2388 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2389
2390 case glslang::EOpConvFloatToBool:
2391 zero = builder.makeFloatConstant(0.0F);
2392 zero = makeSmearedConstant(zero, vectorSize);
2393 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2394
2395 case glslang::EOpConvDoubleToBool:
2396 zero = builder.makeDoubleConstant(0.0);
2397 zero = makeSmearedConstant(zero, vectorSize);
2398 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2399
2400 case glslang::EOpConvBoolToFloat:
2401 convOp = spv::OpSelect;
2402 zero = builder.makeFloatConstant(0.0);
2403 one = builder.makeFloatConstant(1.0);
2404 break;
2405 case glslang::EOpConvBoolToDouble:
2406 convOp = spv::OpSelect;
2407 zero = builder.makeDoubleConstant(0.0);
2408 one = builder.makeDoubleConstant(1.0);
2409 break;
2410 case glslang::EOpConvBoolToInt:
2411 zero = builder.makeIntConstant(0);
2412 one = builder.makeIntConstant(1);
2413 convOp = spv::OpSelect;
2414 break;
2415 case glslang::EOpConvBoolToUint:
2416 zero = builder.makeUintConstant(0);
2417 one = builder.makeUintConstant(1);
2418 convOp = spv::OpSelect;
2419 break;
2420
2421 case glslang::EOpConvIntToFloat:
2422 case glslang::EOpConvIntToDouble:
2423 convOp = spv::OpConvertSToF;
2424 break;
2425
2426 case glslang::EOpConvUintToFloat:
2427 case glslang::EOpConvUintToDouble:
2428 convOp = spv::OpConvertUToF;
2429 break;
2430
2431 case glslang::EOpConvDoubleToFloat:
2432 case glslang::EOpConvFloatToDouble:
2433 convOp = spv::OpFConvert;
2434 break;
2435
2436 case glslang::EOpConvFloatToInt:
2437 case glslang::EOpConvDoubleToInt:
2438 convOp = spv::OpConvertFToS;
2439 break;
2440
2441 case glslang::EOpConvUintToInt:
2442 case glslang::EOpConvIntToUint:
2443 convOp = spv::OpBitcast;
2444 break;
2445
2446 case glslang::EOpConvFloatToUint:
2447 case glslang::EOpConvDoubleToUint:
2448 convOp = spv::OpConvertFToU;
2449 break;
2450 default:
2451 break;
2452 }
2453
2454 spv::Id result = 0;
2455 if (convOp == spv::OpNop)
2456 return result;
2457
2458 if (convOp == spv::OpSelect) {
2459 zero = makeSmearedConstant(zero, vectorSize);
2460 one = makeSmearedConstant(one, vectorSize);
2461 result = builder.createTriOp(convOp, destType, operand, one, zero);
2462 } else
2463 result = builder.createUnaryOp(convOp, destType, operand);
2464
2465 builder.setPrecision(result, precision);
2466
2467 return result;
2468}
2469
2470spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2471{
2472 if (vectorSize == 0)
2473 return constant;
2474
2475 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2476 std::vector<spv::Id> components;
2477 for (int c = 0; c < vectorSize; ++c)
2478 components.push_back(constant);
2479 return builder.makeCompositeConstant(vectorTypeId, components);
2480}
2481
John Kessenich426394d2015-07-23 10:22:48 -06002482// For glslang ops that map to SPV atomic opCodes
2483spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands)
2484{
2485 spv::Op opCode = spv::OpNop;
2486
2487 switch (op) {
2488 case glslang::EOpAtomicAdd:
2489 opCode = spv::OpAtomicIAdd;
2490 break;
2491 case glslang::EOpAtomicMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002492 opCode = spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002493 break;
2494 case glslang::EOpAtomicMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002495 opCode = spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002496 break;
2497 case glslang::EOpAtomicAnd:
2498 opCode = spv::OpAtomicAnd;
2499 break;
2500 case glslang::EOpAtomicOr:
2501 opCode = spv::OpAtomicOr;
2502 break;
2503 case glslang::EOpAtomicXor:
2504 opCode = spv::OpAtomicXor;
2505 break;
2506 case glslang::EOpAtomicExchange:
2507 opCode = spv::OpAtomicExchange;
2508 break;
2509 case glslang::EOpAtomicCompSwap:
2510 opCode = spv::OpAtomicCompareExchange;
2511 break;
2512 case glslang::EOpAtomicCounterIncrement:
2513 opCode = spv::OpAtomicIIncrement;
2514 break;
2515 case glslang::EOpAtomicCounterDecrement:
2516 opCode = spv::OpAtomicIDecrement;
2517 break;
2518 case glslang::EOpAtomicCounter:
2519 opCode = spv::OpAtomicLoad;
2520 break;
2521 default:
2522 spv::MissingFunctionality("missing nested atomic");
2523 break;
2524 }
2525
2526 // Sort out the operands
2527 // - mapping from glslang -> SPV
2528 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06002529 // - compare-exchange swaps the value and comparator
2530 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06002531 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2532 auto opIt = operands.begin(); // walk the glslang operands
2533 spvAtomicOperands.push_back(*(opIt++));
John Kessenich5e4b1242015-08-06 22:53:06 -06002534 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2535 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
John Kessenich3e60a6f2015-09-14 22:45:16 -06002536 if (opCode == spv::OpAtomicCompareExchange) {
2537 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
2538 spvAtomicOperands.push_back(*(opIt + 1));
2539 spvAtomicOperands.push_back(*opIt);
2540 opIt += 2;
2541 }
John Kessenich426394d2015-07-23 10:22:48 -06002542
John Kessenich3e60a6f2015-09-14 22:45:16 -06002543 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06002544 for (; opIt != operands.end(); ++opIt)
2545 spvAtomicOperands.push_back(*opIt);
2546
2547 return builder.createOp(opCode, typeId, spvAtomicOperands);
2548}
2549
John Kessenich5e4b1242015-08-06 22:53:06 -06002550spv::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 -06002551{
John Kessenich5e4b1242015-08-06 22:53:06 -06002552 bool isUnsigned = typeProxy == glslang::EbtUint;
2553 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2554
John Kessenich140f3df2015-06-26 16:58:36 -06002555 spv::Op opCode = spv::OpNop;
2556 int libCall = -1;
2557
2558 switch (op) {
2559 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002560 if (isFloat)
2561 libCall = spv::GLSLstd450FMin;
2562 else if (isUnsigned)
2563 libCall = spv::GLSLstd450UMin;
2564 else
2565 libCall = spv::GLSLstd450SMin;
John Kessenich140f3df2015-06-26 16:58:36 -06002566 break;
2567 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002568 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002569 break;
2570 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002571 if (isFloat)
2572 libCall = spv::GLSLstd450FMax;
2573 else if (isUnsigned)
2574 libCall = spv::GLSLstd450UMax;
2575 else
2576 libCall = spv::GLSLstd450SMax;
John Kessenich140f3df2015-06-26 16:58:36 -06002577 break;
2578 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002579 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002580 break;
2581 case glslang::EOpDot:
2582 opCode = spv::OpDot;
2583 break;
2584 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002585 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002586 break;
2587
2588 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002589 if (isFloat)
2590 libCall = spv::GLSLstd450FClamp;
2591 else if (isUnsigned)
2592 libCall = spv::GLSLstd450UClamp;
2593 else
2594 libCall = spv::GLSLstd450SClamp;
John Kessenich140f3df2015-06-26 16:58:36 -06002595 break;
2596 case glslang::EOpMix:
John Kessenich5e4b1242015-08-06 22:53:06 -06002597 libCall = spv::GLSLstd450Mix;
John Kessenich140f3df2015-06-26 16:58:36 -06002598 break;
2599 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002600 libCall = spv::GLSLstd450Step;
John Kessenich140f3df2015-06-26 16:58:36 -06002601 break;
2602 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002603 libCall = spv::GLSLstd450SmoothStep;
John Kessenich140f3df2015-06-26 16:58:36 -06002604 break;
2605
2606 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002607 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002608 break;
2609 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002610 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002611 break;
2612 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002613 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002614 break;
2615 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002616 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002617 break;
2618 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002619 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002620 break;
John Kessenich426394d2015-07-23 10:22:48 -06002621
John Kessenich140f3df2015-06-26 16:58:36 -06002622 default:
2623 return 0;
2624 }
2625
2626 spv::Id id = 0;
2627 if (libCall >= 0)
2628 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, operands);
2629 else {
2630 switch (operands.size()) {
2631 case 0:
2632 // should all be handled by visitAggregate and createNoArgOperation
2633 assert(0);
2634 return 0;
2635 case 1:
2636 // should all be handled by createUnaryOperation
2637 assert(0);
2638 return 0;
2639 case 2:
2640 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
2641 break;
2642 case 3:
John Kessenich426394d2015-07-23 10:22:48 -06002643 id = builder.createTriOp(opCode, typeId, operands[0], operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002644 break;
2645 default:
2646 // These do not exist yet
2647 assert(0 && "operation with more than 3 operands");
2648 break;
2649 }
2650 }
2651
2652 builder.setPrecision(id, precision);
2653
2654 return id;
2655}
2656
2657// Intrinsics with no arguments, no return value, and no precision.
2658spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
2659{
2660 // TODO: get the barrier operands correct
2661
2662 switch (op) {
2663 case glslang::EOpEmitVertex:
2664 builder.createNoResultOp(spv::OpEmitVertex);
2665 return 0;
2666 case glslang::EOpEndPrimitive:
2667 builder.createNoResultOp(spv::OpEndPrimitive);
2668 return 0;
2669 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002670 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
2671 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06002672 return 0;
2673 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002674 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06002675 return 0;
2676 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06002677 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002678 return 0;
2679 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06002680 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002681 return 0;
2682 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06002683 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002684 return 0;
2685 case glslang::EOpMemoryBarrierShared:
John Kessenich5e4b1242015-08-06 22:53:06 -06002686 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupLocalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002687 return 0;
2688 case glslang::EOpGroupMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002689 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupGlobalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002690 return 0;
2691 default:
2692 spv::MissingFunctionality("operation with no arguments");
2693 return 0;
2694 }
2695}
2696
2697spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
2698{
John Kessenich2f273362015-07-18 22:34:27 -06002699 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06002700 spv::Id id;
2701 if (symbolValues.end() != iter) {
2702 id = iter->second;
2703 return id;
2704 }
2705
2706 // it was not found, create it
2707 id = createSpvVariable(symbol);
2708 symbolValues[symbol->getId()] = id;
2709
2710 if (! symbol->getType().isStruct()) {
2711 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
2712 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
2713 if (symbol->getQualifier().hasLocation())
2714 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
2715 if (symbol->getQualifier().hasIndex())
2716 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
2717 if (symbol->getQualifier().hasComponent())
2718 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
2719 if (glslangIntermediate->getXfbMode()) {
2720 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002721 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002722 if (symbol->getQualifier().hasXfbBuffer())
2723 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2724 if (symbol->getQualifier().hasXfbOffset())
2725 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
2726 }
2727 }
2728
2729 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
2730 if (symbol->getQualifier().hasStream())
2731 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
2732 if (symbol->getQualifier().hasSet())
2733 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
2734 if (symbol->getQualifier().hasBinding())
2735 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
2736 if (glslangIntermediate->getXfbMode()) {
2737 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002738 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002739 if (symbol->getQualifier().hasXfbBuffer())
2740 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2741 }
2742
2743 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06002744 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06002745 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06002746 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06002747
2748 if (linkageOnly)
2749 builder.addDecoration(id, spv::DecorationNoStaticUse);
2750
2751 return id;
2752}
2753
2754void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
2755{
2756 if (dec != spv::BadValue)
2757 builder.addDecoration(id, dec);
2758}
2759
2760void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
2761{
2762 if (dec != spv::BadValue)
2763 builder.addMemberDecoration(id, (unsigned)member, dec);
2764}
2765
2766// Use 'consts' as the flattened glslang source of scalar constants to recursively
2767// build the aggregate SPIR-V constant.
2768//
2769// If there are not enough elements present in 'consts', 0 will be substituted;
2770// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
2771//
2772spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst)
2773{
2774 // vector of constants for SPIR-V
2775 std::vector<spv::Id> spvConsts;
2776
2777 // Type is used for struct and array constants
2778 spv::Id typeId = convertGlslangToSpvType(glslangType);
2779
2780 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002781 glslang::TType elementType(glslangType, 0);
2782 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich140f3df2015-06-26 16:58:36 -06002783 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst));
2784 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002785 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06002786 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
2787 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst));
2788 } else if (glslangType.getStruct()) {
2789 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
2790 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
2791 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst));
2792 } else if (glslangType.isVector()) {
2793 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
2794 bool zero = nextConst >= consts.size();
2795 switch (glslangType.getBasicType()) {
2796 case glslang::EbtInt:
2797 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
2798 break;
2799 case glslang::EbtUint:
2800 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
2801 break;
2802 case glslang::EbtFloat:
2803 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
2804 break;
2805 case glslang::EbtDouble:
2806 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
2807 break;
2808 case glslang::EbtBool:
2809 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
2810 break;
2811 default:
2812 spv::MissingFunctionality("constant vector type");
2813 break;
2814 }
2815 ++nextConst;
2816 }
2817 } else {
2818 // we have a non-aggregate (scalar) constant
2819 bool zero = nextConst >= consts.size();
2820 spv::Id scalar = 0;
2821 switch (glslangType.getBasicType()) {
2822 case glslang::EbtInt:
2823 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst());
2824 break;
2825 case glslang::EbtUint:
2826 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst());
2827 break;
2828 case glslang::EbtFloat:
2829 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst());
2830 break;
2831 case glslang::EbtDouble:
2832 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst());
2833 break;
2834 case glslang::EbtBool:
2835 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst());
2836 break;
2837 default:
2838 spv::MissingFunctionality("constant scalar type");
2839 break;
2840 }
2841 ++nextConst;
2842 return scalar;
2843 }
2844
2845 return builder.makeCompositeConstant(typeId, spvConsts);
2846}
2847
2848}; // end anonymous namespace
2849
2850namespace glslang {
2851
John Kessenich68d78fd2015-07-12 19:28:10 -06002852void GetSpirvVersion(std::string& version)
2853{
John Kessenich9e55f632015-07-15 10:03:39 -06002854 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06002855 char buf[bufSize];
John Kessenich9e55f632015-07-15 10:03:39 -06002856 snprintf(buf, bufSize, "%d, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06002857 version = buf;
2858}
2859
John Kessenich140f3df2015-06-26 16:58:36 -06002860// Write SPIR-V out to a binary file
2861void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
2862{
2863 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06002864 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06002865 for (int i = 0; i < (int)spirv.size(); ++i) {
2866 unsigned int word = spirv[i];
2867 out.write((const char*)&word, 4);
2868 }
2869 out.close();
2870}
2871
2872//
2873// Set up the glslang traversal
2874//
2875void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
2876{
2877 TIntermNode* root = intermediate.getTreeRoot();
2878
2879 if (root == 0)
2880 return;
2881
2882 glslang::GetThreadPoolAllocator().push();
2883
2884 TGlslangToSpvTraverser it(&intermediate);
2885
2886 root->traverse(&it);
2887
2888 it.dumpSpv(spirv);
2889
2890 glslang::GetThreadPoolAllocator().pop();
2891}
2892
2893}; // end namespace glslang