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