blob: baa6dea362fe420d0c880c86fb638a2463104c78 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
2//Copyright (C) 2014 LunarG, Inc.
3//
4//All rights reserved.
5//
6//Redistribution and use in source and binary forms, with or without
7//modification, are permitted provided that the following conditions
8//are met:
9//
10// Redistributions of source code must retain the above copyright
11// notice, this list of conditions and the following disclaimer.
12//
13// Redistributions in binary form must reproduce the above
14// copyright notice, this list of conditions and the following
15// disclaimer in the documentation and/or other materials provided
16// with the distribution.
17//
18// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
19// contributors may be used to endorse or promote products derived
20// from this software without specific prior written permission.
21//
22//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
32//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33//POSSIBILITY OF SUCH DAMAGE.
34
35//
36// Author: John Kessenich, LunarG
37//
38// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
46 #include "GLSL.std.450.h"
47}
John Kessenich140f3df2015-06-26 16:58:36 -060048
49// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020050#include "../glslang/MachineIndependent/localintermediate.h"
51#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060052#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060053
54#include <string>
55#include <map>
56#include <list>
57#include <vector>
58#include <stack>
59#include <fstream>
60
61namespace {
62
63const int GlslangMagic = 0x51a;
64
65//
66// The main holder of information for translating glslang to SPIR-V.
67//
68// Derives from the AST walking base class.
69//
70class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
71public:
72 TGlslangToSpvTraverser(const glslang::TIntermediate*);
73 virtual ~TGlslangToSpvTraverser();
74
75 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
76 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
77 void visitConstantUnion(glslang::TIntermConstantUnion*);
78 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
79 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
80 void visitSymbol(glslang::TIntermSymbol* symbol);
81 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
82 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
83 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
84
85 void dumpSpv(std::vector<unsigned int>& out) { builder.dump(out); }
86
87protected:
88 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
89 spv::Id getSampledType(const glslang::TSampler&);
90 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenich5e4b1242015-08-06 22:53:06 -060091 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset);
John Kessenich140f3df2015-06-26 16:58:36 -060092
93 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
94 void makeFunctions(const glslang::TIntermSequence&);
95 void makeGlobalInitializers(const glslang::TIntermSequence&);
96 void visitFunctions(const glslang::TIntermSequence&);
97 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xufc618912015-09-09 16:42:49 +080098 void translateArguments(glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -060099 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
100 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600101 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
102
103 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
104 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, bool isFloat);
105 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
106 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich426394d2015-07-23 10:22:48 -0600107 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600108 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600109 spv::Id createNoArgOperation(glslang::TOperator op);
110 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
111 void addDecoration(spv::Id id, spv::Decoration dec);
112 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
113 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst);
114
115 spv::Function* shaderEntry;
116 int sequenceDepth;
117
118 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
119 spv::Builder builder;
120 bool inMain;
121 bool mainTerminated;
122 bool linkageOnly;
123 const glslang::TIntermediate* glslangIntermediate;
124 spv::Id stdBuiltins;
125
John Kessenich2f273362015-07-18 22:34:27 -0600126 std::unordered_map<int, spv::Id> symbolValues;
127 std::unordered_set<int> constReadOnlyParameters; // set of formal function parameters that have glslang qualifier constReadOnly, so we know they are not local function "const" that are write-once
128 std::unordered_map<std::string, spv::Function*> functionMap;
129 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap;
130 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600131 std::stack<bool> breakForLoop; // false means break for switch
132 std::stack<glslang::TIntermTyped*> loopTerminal; // code from the last part of a for loop: for(...; ...; terminal), needed for e.g., continue };
133};
134
135//
136// Helper functions for translating glslang representations to SPIR-V enumerants.
137//
138
139// Translate glslang profile to SPIR-V source language.
140spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
141{
142 switch (profile) {
143 case ENoProfile:
144 case ECoreProfile:
145 case ECompatibilityProfile:
146 return spv::SourceLanguageGLSL;
147 case EEsProfile:
148 return spv::SourceLanguageESSL;
149 default:
150 return spv::SourceLanguageUnknown;
151 }
152}
153
154// Translate glslang language (stage) to SPIR-V execution model.
155spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
156{
157 switch (stage) {
158 case EShLangVertex: return spv::ExecutionModelVertex;
159 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
160 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
161 case EShLangGeometry: return spv::ExecutionModelGeometry;
162 case EShLangFragment: return spv::ExecutionModelFragment;
163 case EShLangCompute: return spv::ExecutionModelGLCompute;
164 default:
165 spv::MissingFunctionality("GLSL stage");
166 return spv::ExecutionModelFragment;
167 }
168}
169
170// Translate glslang type to SPIR-V storage class.
171spv::StorageClass TranslateStorageClass(const glslang::TType& type)
172{
173 if (type.getQualifier().isPipeInput())
174 return spv::StorageClassInput;
175 else if (type.getQualifier().isPipeOutput())
176 return spv::StorageClassOutput;
177 else if (type.getQualifier().isUniformOrBuffer()) {
178 if (type.getBasicType() == glslang::EbtBlock)
179 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800180 else if (type.getBasicType() == glslang::EbtAtomicUint)
181 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600182 else
183 return spv::StorageClassUniformConstant;
184 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
185 } else {
186 switch (type.getQualifier().storage) {
187 case glslang::EvqShared: return spv::StorageClassWorkgroupLocal; break;
188 case glslang::EvqGlobal: return spv::StorageClassPrivateGlobal;
189 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
190 case glslang::EvqTemporary: return spv::StorageClassFunction;
191 default:
192 spv::MissingFunctionality("unknown glslang storage class");
193 return spv::StorageClassFunction;
194 }
195 }
196}
197
198// Translate glslang sampler type to SPIR-V dimensionality.
199spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
200{
201 switch (sampler.dim) {
202 case glslang::Esd1D: return spv::Dim1D;
203 case glslang::Esd2D: return spv::Dim2D;
204 case glslang::Esd3D: return spv::Dim3D;
205 case glslang::EsdCube: return spv::DimCube;
206 case glslang::EsdRect: return spv::DimRect;
207 case glslang::EsdBuffer: return spv::DimBuffer;
208 default:
209 spv::MissingFunctionality("unknown sampler dimension");
210 return spv::Dim2D;
211 }
212}
213
214// Translate glslang type to SPIR-V precision decorations.
215spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
216{
217 switch (type.getQualifier().precision) {
John Kessenich5e4b1242015-08-06 22:53:06 -0600218 case glslang::EpqLow: return spv::DecorationRelaxedPrecision; // TODO: Map instead to 16-bit types?
219 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
220 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600221 default:
222 return spv::NoPrecision;
223 }
224}
225
226// Translate glslang type to SPIR-V block decorations.
227spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
228{
229 if (type.getBasicType() == glslang::EbtBlock) {
230 switch (type.getQualifier().storage) {
231 case glslang::EvqUniform: return spv::DecorationBlock;
232 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
233 case glslang::EvqVaryingIn: return spv::DecorationBlock;
234 case glslang::EvqVaryingOut: return spv::DecorationBlock;
235 default:
236 spv::MissingFunctionality("kind of block");
237 break;
238 }
239 }
240
241 return (spv::Decoration)spv::BadValue;
242}
243
244// Translate glslang type to SPIR-V layout decorations.
245spv::Decoration TranslateLayoutDecoration(const glslang::TType& type)
246{
247 if (type.isMatrix()) {
248 switch (type.getQualifier().layoutMatrix) {
249 case glslang::ElmRowMajor:
250 return spv::DecorationRowMajor;
251 default:
252 return spv::DecorationColMajor;
253 }
254 } else {
255 switch (type.getBasicType()) {
256 default:
257 return (spv::Decoration)spv::BadValue;
258 break;
259 case glslang::EbtBlock:
260 switch (type.getQualifier().storage) {
261 case glslang::EvqUniform:
262 case glslang::EvqBuffer:
263 switch (type.getQualifier().layoutPacking) {
264 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
266 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600267 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600268 }
269 case glslang::EvqVaryingIn:
270 case glslang::EvqVaryingOut:
271 if (type.getQualifier().layoutPacking != glslang::ElpNone)
272 spv::MissingFunctionality("in/out block layout");
273 return (spv::Decoration)spv::BadValue;
274 default:
275 spv::MissingFunctionality("block storage qualification");
276 return (spv::Decoration)spv::BadValue;
277 }
278 }
279 }
280}
281
282// Translate glslang type to SPIR-V interpolation decorations.
283spv::Decoration TranslateInterpolationDecoration(const glslang::TType& type)
284{
285 if (type.getQualifier().smooth)
286 return spv::DecorationSmooth;
287 if (type.getQualifier().nopersp)
288 return spv::DecorationNoperspective;
289 else if (type.getQualifier().patch)
290 return spv::DecorationPatch;
291 else if (type.getQualifier().flat)
292 return spv::DecorationFlat;
293 else if (type.getQualifier().centroid)
294 return spv::DecorationCentroid;
295 else if (type.getQualifier().sample)
296 return spv::DecorationSample;
297 else
298 return (spv::Decoration)spv::BadValue;
299}
300
301// If glslang type is invaraiant, return SPIR-V invariant decoration.
302spv::Decoration TranslateInvariantDecoration(const glslang::TType& type)
303{
304 if (type.getQualifier().invariant)
305 return spv::DecorationInvariant;
306 else
307 return (spv::Decoration)spv::BadValue;
308}
309
310// Translate glslang built-in variable to SPIR-V built in decoration.
311spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
312{
313 switch (builtIn) {
314 case glslang::EbvPosition: return spv::BuiltInPosition;
315 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600316 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
317 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
318 case glslang::EbvVertexId: return spv::BuiltInVertexId;
319 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
320 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
321 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
322 case glslang::EbvLayer: return spv::BuiltInLayer;
323 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
324 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
325 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
326 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
327 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
328 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
329 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
330 case glslang::EbvFace: return spv::BuiltInFrontFacing;
331 case glslang::EbvSampleId: return spv::BuiltInSampleId;
332 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
333 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
334 case glslang::EbvFragColor: return spv::BuiltInFragColor;
335 case glslang::EbvFragData: return spv::BuiltInFragColor;
336 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
337 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
338 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
339 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
340 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
341 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
342 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
343 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
344 default: return (spv::BuiltIn)spv::BadValue;
345 }
346}
347
Rex Xufc618912015-09-09 16:42:49 +0800348// Translate glslang image layout format to SPIR-V image format.
349spv::ImageFormat TranslateImageFormat(const glslang::TType& type)
350{
351 assert(type.getBasicType() == glslang::EbtSampler);
352
353 switch (type.getQualifier().layoutFormat) {
354 case glslang::ElfNone: return spv::ImageFormatUnknown;
355 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
356 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
357 case glslang::ElfR32f: return spv::ImageFormatR32f;
358 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
359 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
360 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
361 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
362 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
363 case glslang::ElfR16f: return spv::ImageFormatR16f;
364 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
365 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
366 case glslang::ElfRg16: return spv::ImageFormatRg16;
367 case glslang::ElfRg8: return spv::ImageFormatRg8;
368 case glslang::ElfR16: return spv::ImageFormatR16;
369 case glslang::ElfR8: return spv::ImageFormatR8;
370 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
371 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
372 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
373 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
374 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
375 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
376 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
377 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
378 case glslang::ElfR32i: return spv::ImageFormatR32i;
379 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
380 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
381 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
382 case glslang::ElfR16i: return spv::ImageFormatR16i;
383 case glslang::ElfR8i: return spv::ImageFormatR8i;
384 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
385 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
386 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
387 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
388 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
389 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
390 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
391 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
392 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
393 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
394 default: return (spv::ImageFormat)spv::BadValue;
395 }
396}
397
John Kessenich140f3df2015-06-26 16:58:36 -0600398//
399// Implement the TGlslangToSpvTraverser class.
400//
401
402TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
403 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
404 builder(GlslangMagic),
405 inMain(false), mainTerminated(false), linkageOnly(false),
406 glslangIntermediate(glslangIntermediate)
407{
408 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
409
410 builder.clearAccessChain();
411 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
412 stdBuiltins = builder.import("GLSL.std.450");
413 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
414 shaderEntry = builder.makeMain();
John Kessenich5e4b1242015-08-06 22:53:06 -0600415 builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600416
417 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600418 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
419 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600420 builder.addSourceExtension(it->c_str());
421
422 // Add the top-level modes for this shader.
423
424 if (glslangIntermediate->getXfbMode())
425 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
426
427 unsigned int mode;
428 switch (glslangIntermediate->getStage()) {
429 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600430 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600431 break;
432
433 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600434 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600435 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
436 break;
437
438 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600439 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600440 switch (glslangIntermediate->getInputPrimitive()) {
441 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
442 case glslang::ElgQuads: mode = spv::ExecutionModeInputQuads; break;
443 case glslang::ElgIsolines: mode = spv::ExecutionModeInputIsolines; break;
444 default: mode = spv::BadValue; break;
445 }
446 if (mode != spv::BadValue)
447 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
448
449 // TODO
450 //builder.addExecutionMode(spv::VertexSpacingMdName, glslangIntermediate->getVertexSpacing());
451 //builder.addExecutionMode(spv::VertexOrderMdName, glslangIntermediate->getVertexOrder());
452 //builder.addExecutionMode(spv::PointModeMdName, glslangIntermediate->getPointMode());
453 break;
454
455 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600456 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600457 switch (glslangIntermediate->getInputPrimitive()) {
458 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
459 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
460 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
461 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
462 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
463 default: mode = spv::BadValue; break;
464 }
465 if (mode != spv::BadValue)
466 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
467 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
468
469 switch (glslangIntermediate->getOutputPrimitive()) {
470 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
471 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
472 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
473 default: mode = spv::BadValue; break;
474 }
475 if (mode != spv::BadValue)
476 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
477 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
478 break;
479
480 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600481 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600482 if (glslangIntermediate->getPixelCenterInteger())
483 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
484 if (glslangIntermediate->getOriginUpperLeft())
485 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600486 else
487 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kessenich140f3df2015-06-26 16:58:36 -0600488 break;
489
490 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600491 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600492 break;
493
494 default:
495 break;
496 }
497
498}
499
500TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
501{
502 if (! mainTerminated) {
503 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
504 builder.setBuildPoint(lastMainBlock);
505 builder.leaveFunction(true);
506 }
507}
508
509//
510// Implement the traversal functions.
511//
512// Return true from interior nodes to have the external traversal
513// continue on to children. Return false if children were
514// already processed.
515//
516
517//
518// Symbols can turn into
519// - uniform/input reads
520// - output writes
521// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
522// - something simple that degenerates into the last bullet
523//
524void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
525{
526 // getSymbolId() will set up all the IO decorations on the first call.
527 // Formal function parameters were mapped during makeFunctions().
528 spv::Id id = getSymbolId(symbol);
529
530 if (! linkageOnly) {
531 // Prepare to generate code for the access
532
533 // L-value chains will be computed left to right. We're on the symbol now,
534 // which is the left-most part of the access chain, so now is "clear" time,
535 // followed by setting the base.
536 builder.clearAccessChain();
537
538 // For now, we consider all user variables as being in memory, so they are pointers,
539 // except for "const in" arguments to a function, which are an intermediate object.
540 // See comments in handleUserFunctionCall().
541 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
542 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
543 builder.setAccessChainRValue(id);
544 else
545 builder.setAccessChainLValue(id);
546 }
547}
548
549bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
550{
551 // First, handle special cases
552 switch (node->getOp()) {
553 case glslang::EOpAssign:
554 case glslang::EOpAddAssign:
555 case glslang::EOpSubAssign:
556 case glslang::EOpMulAssign:
557 case glslang::EOpVectorTimesMatrixAssign:
558 case glslang::EOpVectorTimesScalarAssign:
559 case glslang::EOpMatrixTimesScalarAssign:
560 case glslang::EOpMatrixTimesMatrixAssign:
561 case glslang::EOpDivAssign:
562 case glslang::EOpModAssign:
563 case glslang::EOpAndAssign:
564 case glslang::EOpInclusiveOrAssign:
565 case glslang::EOpExclusiveOrAssign:
566 case glslang::EOpLeftShiftAssign:
567 case glslang::EOpRightShiftAssign:
568 // A bin-op assign "a += b" means the same thing as "a = a + b"
569 // where a is evaluated before b. For a simple assignment, GLSL
570 // says to evaluate the left before the right. So, always, left
571 // node then right node.
572 {
573 // get the left l-value, save it away
574 builder.clearAccessChain();
575 node->getLeft()->traverse(this);
576 spv::Builder::AccessChain lValue = builder.getAccessChain();
577
578 // evaluate the right
579 builder.clearAccessChain();
580 node->getRight()->traverse(this);
581 spv::Id rValue = builder.accessChainLoad(TranslatePrecisionDecoration(node->getRight()->getType()));
582
583 if (node->getOp() != glslang::EOpAssign) {
584 // the left is also an r-value
585 builder.setAccessChain(lValue);
586 spv::Id leftRValue = builder.accessChainLoad(TranslatePrecisionDecoration(node->getLeft()->getType()));
587
588 // do the operation
589 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
590 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
591 node->getType().getBasicType());
592
593 // these all need their counterparts in createBinaryOperation()
594 if (rValue == 0)
595 spv::MissingFunctionality("createBinaryOperation");
596 }
597
598 // store the result
599 builder.setAccessChain(lValue);
600 builder.accessChainStore(rValue);
601
602 // assignments are expressions having an rValue after they are evaluated...
603 builder.clearAccessChain();
604 builder.setAccessChainRValue(rValue);
605 }
606 return false;
607 case glslang::EOpIndexDirect:
608 case glslang::EOpIndexDirectStruct:
609 {
610 // Get the left part of the access chain.
611 node->getLeft()->traverse(this);
612
613 // Add the next element in the chain
614
615 int index = 0;
616 if (node->getRight()->getAsConstantUnion() == 0)
617 spv::MissingFunctionality("direct index without a constant node");
618 else
619 index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
620
621 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
622 // This may be, e.g., an anonymous block-member selection, which generally need
623 // index remapping due to hidden members in anonymous blocks.
624 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
625 if (remapper.size() == 0)
626 spv::MissingFunctionality("block without member remapping");
627 else
628 index = remapper[index];
629 }
630
631 if (! node->getLeft()->getType().isArray() &&
632 node->getLeft()->getType().isVector() &&
633 node->getOp() == glslang::EOpIndexDirect) {
634 // This is essentially a hard-coded vector swizzle of size 1,
635 // so short circuit the access-chain stuff with a swizzle.
636 std::vector<unsigned> swizzle;
637 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
638 builder.accessChainPushSwizzle(swizzle);
639 } else {
640 // normal case for indexing array or structure or block
641 builder.accessChainPush(builder.makeIntConstant(index), convertGlslangToSpvType(node->getType()));
642 }
643 }
644 return false;
645 case glslang::EOpIndexIndirect:
646 {
647 // Structure or array or vector indirection.
648 // Will use native SPIR-V access-chain for struct and array indirection;
649 // matrices are arrays of vectors, so will also work for a matrix.
650 // Will use the access chain's 'component' for variable index into a vector.
651
652 // This adapter is building access chains left to right.
653 // Set up the access chain to the left.
654 node->getLeft()->traverse(this);
655
656 // save it so that computing the right side doesn't trash it
657 spv::Builder::AccessChain partial = builder.getAccessChain();
658
659 // compute the next index in the chain
660 builder.clearAccessChain();
661 node->getRight()->traverse(this);
662 spv::Id index = builder.accessChainLoad(TranslatePrecisionDecoration(node->getRight()->getType()));
663
664 // restore the saved access chain
665 builder.setAccessChain(partial);
666
667 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
668 builder.accessChainPushComponent(index);
669 else
670 builder.accessChainPush(index, convertGlslangToSpvType(node->getType()));
671 }
672 return false;
673 case glslang::EOpVectorSwizzle:
674 {
675 node->getLeft()->traverse(this);
676 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
677 std::vector<unsigned> swizzle;
678 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
679 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
680 builder.accessChainPushSwizzle(swizzle);
681 }
682 return false;
683 default:
684 break;
685 }
686
687 // Assume generic binary op...
688
689 // Get the operands
690 builder.clearAccessChain();
691 node->getLeft()->traverse(this);
692 spv::Id left = builder.accessChainLoad(TranslatePrecisionDecoration(node->getLeft()->getType()));
693
694 builder.clearAccessChain();
695 node->getRight()->traverse(this);
696 spv::Id right = builder.accessChainLoad(TranslatePrecisionDecoration(node->getRight()->getType()));
697
698 spv::Id result;
699 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
700
701 result = createBinaryOperation(node->getOp(), precision,
702 convertGlslangToSpvType(node->getType()), left, right,
703 node->getLeft()->getType().getBasicType());
704
705 if (! result) {
706 spv::MissingFunctionality("glslang binary operation");
707 } else {
708 builder.clearAccessChain();
709 builder.setAccessChainRValue(result);
710
711 return false;
712 }
713
714 return true;
715}
716
717bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
718{
John Kessenichfc51d282015-08-19 13:34:18 -0600719 spv::Id result = spv::NoResult;
720
721 // try texturing first
722 result = createImageTextureFunctionCall(node);
723 if (result != spv::NoResult) {
724 builder.clearAccessChain();
725 builder.setAccessChainRValue(result);
726
727 return false; // done with this node
728 }
729
730 // Non-texturing.
731 // Start by evaluating the operand
732
John Kessenich140f3df2015-06-26 16:58:36 -0600733 builder.clearAccessChain();
734 node->getOperand()->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +0800735 spv::Id operand = spv::NoResult;
736
737 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
738 node->getOp() == glslang::EOpAtomicCounterDecrement ||
739 node->getOp() == glslang::EOpAtomicCounter)
740 operand = builder.accessChainGetLValue(); // Special case l-value operands
741 else
742 operand = builder.accessChainLoad(TranslatePrecisionDecoration(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600743
744 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
745
746 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600747 if (! result)
748 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600749
750 // if not, then possibly an operation
751 if (! result)
John Kessenichfc51d282015-08-19 13:34:18 -0600752 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand,
753 node->getBasicType() == glslang::EbtFloat || node->getBasicType() == glslang::EbtDouble);
John Kessenich140f3df2015-06-26 16:58:36 -0600754
755 if (result) {
756 builder.clearAccessChain();
757 builder.setAccessChainRValue(result);
758
759 return false; // done with this node
760 }
761
762 // it must be a special case, check...
763 switch (node->getOp()) {
764 case glslang::EOpPostIncrement:
765 case glslang::EOpPostDecrement:
766 case glslang::EOpPreIncrement:
767 case glslang::EOpPreDecrement:
768 {
769 // we need the integer value "1" or the floating point "1.0" to add/subtract
770 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
771 builder.makeFloatConstant(1.0F) :
772 builder.makeIntConstant(1);
773 glslang::TOperator op;
774 if (node->getOp() == glslang::EOpPreIncrement ||
775 node->getOp() == glslang::EOpPostIncrement)
776 op = glslang::EOpAdd;
777 else
778 op = glslang::EOpSub;
779
780 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
781 convertGlslangToSpvType(node->getType()), operand, one,
782 node->getType().getBasicType());
783 if (result == 0)
784 spv::MissingFunctionality("createBinaryOperation for unary");
785
786 // The result of operation is always stored, but conditionally the
787 // consumed result. The consumed result is always an r-value.
788 builder.accessChainStore(result);
789 builder.clearAccessChain();
790 if (node->getOp() == glslang::EOpPreIncrement ||
791 node->getOp() == glslang::EOpPreDecrement)
792 builder.setAccessChainRValue(result);
793 else
794 builder.setAccessChainRValue(operand);
795 }
796
797 return false;
798
799 case glslang::EOpEmitStreamVertex:
800 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
801 return false;
802 case glslang::EOpEndStreamPrimitive:
803 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
804 return false;
805
806 default:
807 spv::MissingFunctionality("glslang unary");
808 break;
809 }
810
811 return true;
812}
813
814bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
815{
John Kessenichfc51d282015-08-19 13:34:18 -0600816 spv::Id result = spv::NoResult;
817
818 // try texturing
819 result = createImageTextureFunctionCall(node);
820 if (result != spv::NoResult) {
821 builder.clearAccessChain();
822 builder.setAccessChainRValue(result);
823
824 return false;
825 }
Rex Xufc618912015-09-09 16:42:49 +0800826 else if (node->getOp() == glslang::EOpImageStore)
827 {
828 // "imageStore" is a special case, which has no result
829 return false;
830 }
John Kessenichfc51d282015-08-19 13:34:18 -0600831
John Kessenich140f3df2015-06-26 16:58:36 -0600832 glslang::TOperator binOp = glslang::EOpNull;
833 bool reduceComparison = true;
834 bool isMatrix = false;
835 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600836 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600837
838 assert(node->getOp());
839
840 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
841
842 switch (node->getOp()) {
843 case glslang::EOpSequence:
844 {
845 if (preVisit)
846 ++sequenceDepth;
847 else
848 --sequenceDepth;
849
850 if (sequenceDepth == 1) {
851 // If this is the parent node of all the functions, we want to see them
852 // early, so all call points have actual SPIR-V functions to reference.
853 // In all cases, still let the traverser visit the children for us.
854 makeFunctions(node->getAsAggregate()->getSequence());
855
856 // Also, we want all globals initializers to go into the entry of main(), before
857 // anything else gets there, so visit out of order, doing them all now.
858 makeGlobalInitializers(node->getAsAggregate()->getSequence());
859
860 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
861 // so do them manually.
862 visitFunctions(node->getAsAggregate()->getSequence());
863
864 return false;
865 }
866
867 return true;
868 }
869 case glslang::EOpLinkerObjects:
870 {
871 if (visit == glslang::EvPreVisit)
872 linkageOnly = true;
873 else
874 linkageOnly = false;
875
876 return true;
877 }
878 case glslang::EOpComma:
879 {
880 // processing from left to right naturally leaves the right-most
881 // lying around in the access chain
882 glslang::TIntermSequence& glslangOperands = node->getSequence();
883 for (int i = 0; i < (int)glslangOperands.size(); ++i)
884 glslangOperands[i]->traverse(this);
885
886 return false;
887 }
888 case glslang::EOpFunction:
889 if (visit == glslang::EvPreVisit) {
890 if (isShaderEntrypoint(node)) {
891 inMain = true;
892 builder.setBuildPoint(shaderEntry->getLastBlock());
893 } else {
894 handleFunctionEntry(node);
895 }
896 } else {
897 if (inMain)
898 mainTerminated = true;
899 builder.leaveFunction(inMain);
900 inMain = false;
901 }
902
903 return true;
904 case glslang::EOpParameters:
905 // Parameters will have been consumed by EOpFunction processing, but not
906 // the body, so we still visited the function node's children, making this
907 // child redundant.
908 return false;
909 case glslang::EOpFunctionCall:
910 {
911 if (node->isUserDefined())
912 result = handleUserFunctionCall(node);
John Kessenich140f3df2015-06-26 16:58:36 -0600913
914 if (! result) {
915 spv::MissingFunctionality("glslang function call");
916 glslang::TConstUnionArray emptyConsts;
917 int nextConst = 0;
918 result = createSpvConstant(node->getType(), emptyConsts, nextConst);
919 }
920 builder.clearAccessChain();
921 builder.setAccessChainRValue(result);
922
923 return false;
924 }
925 case glslang::EOpConstructMat2x2:
926 case glslang::EOpConstructMat2x3:
927 case glslang::EOpConstructMat2x4:
928 case glslang::EOpConstructMat3x2:
929 case glslang::EOpConstructMat3x3:
930 case glslang::EOpConstructMat3x4:
931 case glslang::EOpConstructMat4x2:
932 case glslang::EOpConstructMat4x3:
933 case glslang::EOpConstructMat4x4:
934 case glslang::EOpConstructDMat2x2:
935 case glslang::EOpConstructDMat2x3:
936 case glslang::EOpConstructDMat2x4:
937 case glslang::EOpConstructDMat3x2:
938 case glslang::EOpConstructDMat3x3:
939 case glslang::EOpConstructDMat3x4:
940 case glslang::EOpConstructDMat4x2:
941 case glslang::EOpConstructDMat4x3:
942 case glslang::EOpConstructDMat4x4:
943 isMatrix = true;
944 // fall through
945 case glslang::EOpConstructFloat:
946 case glslang::EOpConstructVec2:
947 case glslang::EOpConstructVec3:
948 case glslang::EOpConstructVec4:
949 case glslang::EOpConstructDouble:
950 case glslang::EOpConstructDVec2:
951 case glslang::EOpConstructDVec3:
952 case glslang::EOpConstructDVec4:
953 case glslang::EOpConstructBool:
954 case glslang::EOpConstructBVec2:
955 case glslang::EOpConstructBVec3:
956 case glslang::EOpConstructBVec4:
957 case glslang::EOpConstructInt:
958 case glslang::EOpConstructIVec2:
959 case glslang::EOpConstructIVec3:
960 case glslang::EOpConstructIVec4:
961 case glslang::EOpConstructUint:
962 case glslang::EOpConstructUVec2:
963 case glslang::EOpConstructUVec3:
964 case glslang::EOpConstructUVec4:
965 case glslang::EOpConstructStruct:
966 {
967 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +0800968 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -0600969 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
970 spv::Id constructed;
971 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
972 std::vector<spv::Id> constituents;
973 for (int c = 0; c < (int)arguments.size(); ++c)
974 constituents.push_back(arguments[c]);
975 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
976 } else {
977 if (isMatrix)
978 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
979 else
980 constructed = builder.createConstructor(precision, arguments, resultTypeId);
981 }
982
983 builder.clearAccessChain();
984 builder.setAccessChainRValue(constructed);
985
986 return false;
987 }
988
989 // These six are component-wise compares with component-wise results.
990 // Forward on to createBinaryOperation(), requesting a vector result.
991 case glslang::EOpLessThan:
992 case glslang::EOpGreaterThan:
993 case glslang::EOpLessThanEqual:
994 case glslang::EOpGreaterThanEqual:
995 case glslang::EOpVectorEqual:
996 case glslang::EOpVectorNotEqual:
997 {
998 // Map the operation to a binary
999 binOp = node->getOp();
1000 reduceComparison = false;
1001 switch (node->getOp()) {
1002 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1003 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1004 default: binOp = node->getOp(); break;
1005 }
1006
1007 break;
1008 }
1009 case glslang::EOpMul:
1010 // compontent-wise matrix multiply
1011 binOp = glslang::EOpMul;
1012 break;
1013 case glslang::EOpOuterProduct:
1014 // two vectors multiplied to make a matrix
1015 binOp = glslang::EOpOuterProduct;
1016 break;
1017 case glslang::EOpDot:
1018 {
1019 // for scalar dot product, use multiply
1020 glslang::TIntermSequence& glslangOperands = node->getSequence();
1021 if (! glslangOperands[0]->getAsTyped()->isVector())
1022 binOp = glslang::EOpMul;
1023 break;
1024 }
1025 case glslang::EOpMod:
1026 // when an aggregate, this is the floating-point mod built-in function,
1027 // which can be emitted by the one in createBinaryOperation()
1028 binOp = glslang::EOpMod;
1029 break;
1030 case glslang::EOpArrayLength:
1031 {
1032 glslang::TIntermTyped* typedNode = node->getSequence()[0]->getAsTyped();
1033 assert(typedNode);
John Kessenich65c78a02015-08-10 17:08:55 -06001034 spv::Id length = builder.makeIntConstant(typedNode->getType().getOuterArraySize());
John Kessenich140f3df2015-06-26 16:58:36 -06001035
1036 builder.clearAccessChain();
1037 builder.setAccessChainRValue(length);
1038
1039 return false;
1040 }
1041 case glslang::EOpEmitVertex:
1042 case glslang::EOpEndPrimitive:
1043 case glslang::EOpBarrier:
1044 case glslang::EOpMemoryBarrier:
1045 case glslang::EOpMemoryBarrierAtomicCounter:
1046 case glslang::EOpMemoryBarrierBuffer:
1047 case glslang::EOpMemoryBarrierImage:
1048 case glslang::EOpMemoryBarrierShared:
1049 case glslang::EOpGroupMemoryBarrier:
1050 noReturnValue = true;
1051 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1052 break;
1053
John Kessenich426394d2015-07-23 10:22:48 -06001054 case glslang::EOpAtomicAdd:
1055 case glslang::EOpAtomicMin:
1056 case glslang::EOpAtomicMax:
1057 case glslang::EOpAtomicAnd:
1058 case glslang::EOpAtomicOr:
1059 case glslang::EOpAtomicXor:
1060 case glslang::EOpAtomicExchange:
1061 case glslang::EOpAtomicCompSwap:
1062 atomic = true;
1063 break;
1064
John Kessenichfc51d282015-08-19 13:34:18 -06001065 case glslang::EOpAddCarry:
1066 case glslang::EOpSubBorrow:
1067 case glslang::EOpUMulExtended:
1068 case glslang::EOpIMulExtended:
1069 case glslang::EOpBitfieldExtract:
1070 case glslang::EOpBitfieldInsert:
1071 spv::MissingFunctionality("integer aggregate");
1072 break;
1073
1074 case glslang::EOpFma:
John Kessenich78258d32015-08-19 17:30:12 -06001075 case glslang::EOpFrexp:
1076 case glslang::EOpLdexp:
John Kessenichfc51d282015-08-19 13:34:18 -06001077 spv::MissingFunctionality("fma/frexp/ldexp aggregate");
1078 break;
1079
John Kessenich140f3df2015-06-26 16:58:36 -06001080 default:
1081 break;
1082 }
1083
1084 //
1085 // See if it maps to a regular operation.
1086 //
John Kessenich140f3df2015-06-26 16:58:36 -06001087 if (binOp != glslang::EOpNull) {
1088 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1089 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1090 assert(left && right);
1091
1092 builder.clearAccessChain();
1093 left->traverse(this);
1094 spv::Id leftId = builder.accessChainLoad(TranslatePrecisionDecoration(left->getType()));
1095
1096 builder.clearAccessChain();
1097 right->traverse(this);
1098 spv::Id rightId = builder.accessChainLoad(TranslatePrecisionDecoration(right->getType()));
1099
1100 result = createBinaryOperation(binOp, precision,
1101 convertGlslangToSpvType(node->getType()), leftId, rightId,
1102 left->getType().getBasicType(), reduceComparison);
1103
1104 // code above should only make binOp that exists in createBinaryOperation
1105 if (result == 0)
1106 spv::MissingFunctionality("createBinaryOperation for aggregate");
1107
1108 builder.clearAccessChain();
1109 builder.setAccessChainRValue(result);
1110
1111 return false;
1112 }
1113
John Kessenich426394d2015-07-23 10:22:48 -06001114 //
1115 // Create the list of operands.
1116 //
John Kessenich140f3df2015-06-26 16:58:36 -06001117 glslang::TIntermSequence& glslangOperands = node->getSequence();
1118 std::vector<spv::Id> operands;
1119 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1120 builder.clearAccessChain();
1121 glslangOperands[arg]->traverse(this);
1122
1123 // special case l-value operands; there are just a few
1124 bool lvalue = false;
1125 switch (node->getOp()) {
1126 //case glslang::EOpFrexp:
1127 case glslang::EOpModf:
1128 if (arg == 1)
1129 lvalue = true;
1130 break;
Rex Xud4782c12015-09-06 16:30:11 +08001131 case glslang::EOpAtomicAdd:
1132 case glslang::EOpAtomicMin:
1133 case glslang::EOpAtomicMax:
1134 case glslang::EOpAtomicAnd:
1135 case glslang::EOpAtomicOr:
1136 case glslang::EOpAtomicXor:
1137 case glslang::EOpAtomicExchange:
1138 case glslang::EOpAtomicCompSwap:
1139 if (arg == 0)
1140 lvalue = true;
1141 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001142 //case glslang::EOpUAddCarry:
1143 //case glslang::EOpUSubBorrow:
1144 //case glslang::EOpUMulExtended:
1145 default:
1146 break;
1147 }
1148 if (lvalue)
1149 operands.push_back(builder.accessChainGetLValue());
1150 else
1151 operands.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangOperands[arg]->getAsTyped()->getType())));
1152 }
John Kessenich426394d2015-07-23 10:22:48 -06001153
1154 if (atomic) {
1155 // Handle all atomics
1156 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands);
1157 } else {
1158 // Pass through to generic operations.
1159 switch (glslangOperands.size()) {
1160 case 0:
1161 result = createNoArgOperation(node->getOp());
1162 break;
1163 case 1:
1164 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), node->getType().getBasicType() == glslang::EbtFloat || node->getType().getBasicType() == glslang::EbtDouble);
1165 break;
1166 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001167 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001168 break;
1169 }
John Kessenich140f3df2015-06-26 16:58:36 -06001170 }
1171
1172 if (noReturnValue)
1173 return false;
1174
1175 if (! result) {
1176 spv::MissingFunctionality("glslang aggregate");
1177 return true;
1178 } else {
1179 builder.clearAccessChain();
1180 builder.setAccessChainRValue(result);
1181 return false;
1182 }
1183}
1184
1185bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1186{
1187 // This path handles both if-then-else and ?:
1188 // The if-then-else has a node type of void, while
1189 // ?: has a non-void node type
1190 spv::Id result = 0;
1191 if (node->getBasicType() != glslang::EbtVoid) {
1192 // don't handle this as just on-the-fly temporaries, because there will be two names
1193 // and better to leave SSA to later passes
1194 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1195 }
1196
1197 // emit the condition before doing anything with selection
1198 node->getCondition()->traverse(this);
1199
1200 // make an "if" based on the value created by the condition
1201 spv::Builder::If ifBuilder(builder.accessChainLoad(spv::NoPrecision), builder);
1202
1203 if (node->getTrueBlock()) {
1204 // emit the "then" statement
1205 node->getTrueBlock()->traverse(this);
1206 if (result)
1207 builder.createStore(builder.accessChainLoad(TranslatePrecisionDecoration(node->getTrueBlock()->getAsTyped()->getType())), result);
1208 }
1209
1210 if (node->getFalseBlock()) {
1211 ifBuilder.makeBeginElse();
1212 // emit the "else" statement
1213 node->getFalseBlock()->traverse(this);
1214 if (result)
1215 builder.createStore(builder.accessChainLoad(TranslatePrecisionDecoration(node->getFalseBlock()->getAsTyped()->getType())), result);
1216 }
1217
1218 ifBuilder.makeEndIf();
1219
1220 if (result) {
1221 // GLSL only has r-values as the result of a :?, but
1222 // if we have an l-value, that can be more efficient if it will
1223 // become the base of a complex r-value expression, because the
1224 // next layer copies r-values into memory to use the access-chain mechanism
1225 builder.clearAccessChain();
1226 builder.setAccessChainLValue(result);
1227 }
1228
1229 return false;
1230}
1231
1232bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1233{
1234 // emit and get the condition before doing anything with switch
1235 node->getCondition()->traverse(this);
1236 spv::Id selector = builder.accessChainLoad(TranslatePrecisionDecoration(node->getCondition()->getAsTyped()->getType()));
1237
1238 // browse the children to sort out code segments
1239 int defaultSegment = -1;
1240 std::vector<TIntermNode*> codeSegments;
1241 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1242 std::vector<int> caseValues;
1243 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1244 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1245 TIntermNode* child = *c;
1246 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001247 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001248 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001249 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001250 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1251 } else
1252 codeSegments.push_back(child);
1253 }
1254
1255 // handle the case where the last code segment is missing, due to no code
1256 // statements between the last case and the end of the switch statement
1257 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1258 (int)codeSegments.size() == defaultSegment)
1259 codeSegments.push_back(nullptr);
1260
1261 // make the switch statement
1262 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001263 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001264
1265 // emit all the code in the segments
1266 breakForLoop.push(false);
1267 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1268 builder.nextSwitchSegment(segmentBlocks, s);
1269 if (codeSegments[s])
1270 codeSegments[s]->traverse(this);
1271 else
1272 builder.addSwitchBreak();
1273 }
1274 breakForLoop.pop();
1275
1276 builder.endSwitch(segmentBlocks);
1277
1278 return false;
1279}
1280
1281void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1282{
1283 int nextConst = 0;
1284 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1285
1286 builder.clearAccessChain();
1287 builder.setAccessChainRValue(constant);
1288}
1289
1290bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1291{
1292 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1293 loopTerminal.push(node->getTerminal());
1294
David Netoc22f37c2015-07-15 16:21:26 -04001295 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001296
1297 if (node->getTest()) {
1298 node->getTest()->traverse(this);
1299 // the AST only contained the test computation, not the branch, we have to add it
1300 spv::Id condition = builder.accessChainLoad(TranslatePrecisionDecoration(node->getTest()->getType()));
1301 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001302 } else {
1303 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001304 }
1305
David Netoc22f37c2015-07-15 16:21:26 -04001306 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001307 breakForLoop.push(true);
1308 node->getBody()->traverse(this);
1309 breakForLoop.pop();
1310 }
1311
1312 if (loopTerminal.top())
1313 loopTerminal.top()->traverse(this);
1314
1315 builder.closeLoop();
1316
1317 loopTerminal.pop();
1318
1319 return false;
1320}
1321
1322bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1323{
1324 if (node->getExpression())
1325 node->getExpression()->traverse(this);
1326
1327 switch (node->getFlowOp()) {
1328 case glslang::EOpKill:
1329 builder.makeDiscard();
1330 break;
1331 case glslang::EOpBreak:
1332 if (breakForLoop.top())
1333 builder.createLoopExit();
1334 else
1335 builder.addSwitchBreak();
1336 break;
1337 case glslang::EOpContinue:
1338 if (loopTerminal.top())
1339 loopTerminal.top()->traverse(this);
1340 builder.createLoopContinue();
1341 break;
1342 case glslang::EOpReturn:
1343 if (inMain)
1344 builder.makeMainReturn();
1345 else if (node->getExpression())
1346 builder.makeReturn(false, builder.accessChainLoad(TranslatePrecisionDecoration(node->getExpression()->getType())));
1347 else
1348 builder.makeReturn();
1349
1350 builder.clearAccessChain();
1351 break;
1352
1353 default:
1354 spv::MissingFunctionality("branch type");
1355 break;
1356 }
1357
1358 return false;
1359}
1360
1361spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1362{
1363 // First, steer off constants, which are not SPIR-V variables, but
1364 // can still have a mapping to a SPIR-V Id.
1365 if (node->getQualifier().storage == glslang::EvqConst) {
1366 int nextConst = 0;
1367 return createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1368 }
1369
1370 // Now, handle actual variables
1371 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1372 spv::Id spvType = convertGlslangToSpvType(node->getType());
1373
1374 const char* name = node->getName().c_str();
1375 if (glslang::IsAnonymous(name))
1376 name = "";
1377
1378 return builder.createVariable(storageClass, spvType, name);
1379}
1380
1381// Return type Id of the sampled type.
1382spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1383{
1384 switch (sampler.type) {
1385 case glslang::EbtFloat: return builder.makeFloatType(32);
1386 case glslang::EbtInt: return builder.makeIntType(32);
1387 case glslang::EbtUint: return builder.makeUintType(32);
1388 default:
1389 spv::MissingFunctionality("sampled type");
1390 return builder.makeFloatType(32);
1391 }
1392}
1393
1394// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1395spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1396{
1397 spv::Id spvType = 0;
1398
1399 switch (type.getBasicType()) {
1400 case glslang::EbtVoid:
1401 spvType = builder.makeVoidType();
1402 if (type.isArray())
1403 spv::MissingFunctionality("array of void");
1404 break;
1405 case glslang::EbtFloat:
1406 spvType = builder.makeFloatType(32);
1407 break;
1408 case glslang::EbtDouble:
1409 spvType = builder.makeFloatType(64);
1410 break;
1411 case glslang::EbtBool:
1412 spvType = builder.makeBoolType();
1413 break;
1414 case glslang::EbtInt:
1415 spvType = builder.makeIntType(32);
1416 break;
1417 case glslang::EbtUint:
1418 spvType = builder.makeUintType(32);
1419 break;
John Kessenich426394d2015-07-23 10:22:48 -06001420 case glslang::EbtAtomicUint:
1421 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1422 spvType = builder.makeUintType(32);
1423 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001424 case glslang::EbtSampler:
1425 {
1426 const glslang::TSampler& sampler = type.getSampler();
John Kessenich5e4b1242015-08-06 22:53:06 -06001427 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
Rex Xufc618912015-09-09 16:42:49 +08001428 sampler.image ? 2 : 1, TranslateImageFormat(type));
John Kessenich5e4b1242015-08-06 22:53:06 -06001429 // OpenGL "textures" need to be combined with a sampler
1430 if (! sampler.image)
1431 spvType = builder.makeSampledImageType(spvType);
John Kessenich140f3df2015-06-26 16:58:36 -06001432 }
1433 break;
1434 case glslang::EbtStruct:
1435 case glslang::EbtBlock:
1436 {
1437 // If we've seen this struct type, return it
1438 const glslang::TTypeList* glslangStruct = type.getStruct();
1439 std::vector<spv::Id> structFields;
1440 spvType = structMap[glslangStruct];
1441 if (spvType)
1442 break;
1443
1444 // else, we haven't seen it...
1445
1446 // Create a vector of struct types for SPIR-V to consume
1447 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1448 if (type.getBasicType() == glslang::EbtBlock)
1449 memberRemapper[glslangStruct].resize(glslangStruct->size());
1450 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1451 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1452 if (glslangType.hiddenMember()) {
1453 ++memberDelta;
1454 if (type.getBasicType() == glslang::EbtBlock)
1455 memberRemapper[glslangStruct][i] = -1;
1456 } else {
1457 if (type.getBasicType() == glslang::EbtBlock)
1458 memberRemapper[glslangStruct][i] = i - memberDelta;
1459 structFields.push_back(convertGlslangToSpvType(glslangType));
1460 }
1461 }
1462
1463 // Make the SPIR-V type
1464 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
1465 structMap[glslangStruct] = spvType;
1466
1467 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001468 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001469 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1470 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1471 int member = i;
1472 if (type.getBasicType() == glslang::EbtBlock)
1473 member = memberRemapper[glslangStruct][i];
1474 // using -1 above to indicate a hidden member
1475 if (member >= 0) {
1476 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
1477 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType));
1478 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1479 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1480 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1481 if (glslangType.getQualifier().hasLocation())
1482 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1483 if (glslangType.getQualifier().hasComponent())
1484 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1485 if (glslangType.getQualifier().hasXfbOffset())
1486 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001487 else {
1488 // figure out what to do with offset, which is accumulating
1489 int nextOffset;
1490 updateMemberOffset(type, glslangType, offset, nextOffset);
1491 if (offset >= 0)
1492 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutOffset);
1493 offset = nextOffset;
1494 }
John Kessenich140f3df2015-06-26 16:58:36 -06001495
1496 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001497 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1498 if (builtIn != spv::BadValue)
1499 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001500 }
1501 }
1502
1503 // Decorate the structure
1504 addDecoration(spvType, TranslateLayoutDecoration(type));
1505 addDecoration(spvType, TranslateBlockDecoration(type));
1506 if (type.getQualifier().hasStream())
1507 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1508 if (glslangIntermediate->getXfbMode()) {
1509 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001510 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001511 if (type.getQualifier().hasXfbBuffer())
1512 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1513 }
1514 }
1515 break;
1516 default:
1517 spv::MissingFunctionality("basic type");
1518 break;
1519 }
1520
1521 if (type.isMatrix())
1522 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1523 else {
1524 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1525 if (type.getVectorSize() > 1)
1526 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1527 }
1528
1529 if (type.isArray()) {
1530 unsigned arraySize;
1531 if (! type.isExplicitlySizedArray()) {
1532 spv::MissingFunctionality("Unsized array");
1533 arraySize = 8;
1534 } else
John Kessenich65c78a02015-08-10 17:08:55 -06001535 arraySize = type.getOuterArraySize();
John Kessenich140f3df2015-06-26 16:58:36 -06001536 spvType = builder.makeArrayType(spvType, arraySize);
1537 }
1538
1539 return spvType;
1540}
1541
John Kessenich5e4b1242015-08-06 22:53:06 -06001542// Given a member type of a struct, realign the current offset for it, and compute
1543// the next (not yet aligned) offset for the next member, which will get aligned
1544// on the next call.
1545// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1546// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1547// -1 means a non-forced member offset (no decoration needed).
1548void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset)
1549{
1550 // this will get a positive value when deemed necessary
1551 nextOffset = -1;
1552
1553 bool forceOffset = structType.getQualifier().layoutPacking == glslang::ElpStd140 ||
1554 structType.getQualifier().layoutPacking == glslang::ElpStd430;
1555
1556 // override anything in currentOffset with user-set offset
1557 if (memberType.getQualifier().hasOffset())
1558 currentOffset = memberType.getQualifier().layoutOffset;
1559
1560 // It could be that current linker usage in glslang updated all the layoutOffset,
1561 // in which case the following code does not matter. But, that's not quite right
1562 // once cross-compilation unit GLSL validation is done, as the original user
1563 // settings are needed in layoutOffset, and then the following will come into play.
1564
1565 if (! forceOffset) {
1566 if (! memberType.getQualifier().hasOffset())
1567 currentOffset = -1;
1568
1569 return;
1570 }
1571
1572 // Getting this far means we are forcing offsets
1573 if (currentOffset < 0)
1574 currentOffset = 0;
1575
1576 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1577 // but possibly not yet correctly aligned.
1578
1579 int memberSize;
1580 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, memberType.getQualifier().layoutPacking == glslang::ElpStd140);
1581 glslang::RoundToPow2(currentOffset, memberAlignment);
1582 nextOffset = currentOffset + memberSize;
1583}
1584
John Kessenich140f3df2015-06-26 16:58:36 -06001585bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1586{
1587 return node->getName() == "main(";
1588}
1589
1590// Make all the functions, skeletally, without actually visiting their bodies.
1591void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1592{
1593 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1594 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1595 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1596 continue;
1597
1598 // We're on a user function. Set up the basic interface for the function now,
1599 // so that it's available to call.
1600 // Translating the body will happen later.
1601 //
1602 // Typically (except for a "const in" parameter), an address will be passed to the
1603 // function. What it is an address of varies:
1604 //
1605 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1606 // so that write needs to be to a copy, hence the address of a copy works.
1607 //
1608 // - "const in" parameters can just be the r-value, as no writes need occur.
1609 //
1610 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1611 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1612
1613 std::vector<spv::Id> paramTypes;
1614 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1615
1616 for (int p = 0; p < (int)parameters.size(); ++p) {
1617 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1618 spv::Id typeId = convertGlslangToSpvType(paramType);
1619 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1620 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1621 else
1622 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1623 paramTypes.push_back(typeId);
1624 }
1625
1626 spv::Block* functionBlock;
1627 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1628 paramTypes, &functionBlock);
1629
1630 // Track function to emit/call later
1631 functionMap[glslFunction->getName().c_str()] = function;
1632
1633 // Set the parameter id's
1634 for (int p = 0; p < (int)parameters.size(); ++p) {
1635 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1636 // give a name too
1637 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1638 }
1639 }
1640}
1641
1642// Process all the initializers, while skipping the functions and link objects
1643void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1644{
1645 builder.setBuildPoint(shaderEntry->getLastBlock());
1646 for (int i = 0; i < (int)initializers.size(); ++i) {
1647 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1648 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1649
1650 // We're on a top-level node that's not a function. Treat as an initializer, whose
1651 // code goes into the beginning of main.
1652 initializer->traverse(this);
1653 }
1654 }
1655}
1656
1657// Process all the functions, while skipping initializers.
1658void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1659{
1660 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1661 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1662 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1663 node->traverse(this);
1664 }
1665}
1666
1667void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1668{
1669 // SPIR-V functions should already be in the functionMap from the prepass
1670 // that called makeFunctions().
1671 spv::Function* function = functionMap[node->getName().c_str()];
1672 spv::Block* functionBlock = function->getEntryBlock();
1673 builder.setBuildPoint(functionBlock);
1674}
1675
Rex Xufc618912015-09-09 16:42:49 +08001676void TGlslangToSpvTraverser::translateArguments(glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001677{
Rex Xufc618912015-09-09 16:42:49 +08001678 const glslang::TIntermSequence& glslangArguments = node.getSequence();
John Kessenich140f3df2015-06-26 16:58:36 -06001679 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1680 builder.clearAccessChain();
1681 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001682
1683 // Special case l-value operands
1684 bool lvalue = false;
1685 switch (node.getOp()) {
1686 case glslang::EOpImageAtomicAdd:
1687 case glslang::EOpImageAtomicMin:
1688 case glslang::EOpImageAtomicMax:
1689 case glslang::EOpImageAtomicAnd:
1690 case glslang::EOpImageAtomicOr:
1691 case glslang::EOpImageAtomicXor:
1692 case glslang::EOpImageAtomicExchange:
1693 case glslang::EOpImageAtomicCompSwap:
1694 if (i == 0)
1695 lvalue = true;
1696 break;
1697 default:
1698 break;
1699 }
1700
1701 if (lvalue) {
1702 arguments.push_back(builder.accessChainGetLValue());
1703 }
1704 else {
1705 arguments.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangArguments[i]->getAsTyped()->getType())));
1706 }
John Kessenich140f3df2015-06-26 16:58:36 -06001707 }
1708}
1709
John Kessenichfc51d282015-08-19 13:34:18 -06001710void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001711{
John Kessenichfc51d282015-08-19 13:34:18 -06001712 builder.clearAccessChain();
1713 node.getOperand()->traverse(this);
1714 arguments.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(node.getAsTyped()->getType())));
1715}
John Kessenich140f3df2015-06-26 16:58:36 -06001716
John Kessenichfc51d282015-08-19 13:34:18 -06001717spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1718{
Rex Xufc618912015-09-09 16:42:49 +08001719 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06001720 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001721 }
1722
John Kessenichfc51d282015-08-19 13:34:18 -06001723 // Process a GLSL texturing op (will be SPV image)
John Kessenich140f3df2015-06-26 16:58:36 -06001724
John Kessenichfc51d282015-08-19 13:34:18 -06001725 glslang::TCrackedTextureOp cracked;
1726 node->crackTexture(cracked);
1727
1728 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1729 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1730 std::vector<spv::Id> arguments;
1731 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08001732 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06001733 else
1734 translateArguments(*node->getAsUnaryNode(), arguments);
1735 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1736
1737 spv::Builder::TextureParameters params = { };
1738 params.sampler = arguments[0];
1739
1740 // Check for queries
1741 if (cracked.query) {
1742 switch (node->getOp()) {
1743 case glslang::EOpImageQuerySize:
1744 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001745 if (arguments.size() > 1) {
1746 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001747 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001748 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001749 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001750 case glslang::EOpImageQuerySamples:
1751 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001752 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001753 case glslang::EOpTextureQueryLod:
1754 params.coords = arguments[1];
1755 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1756 case glslang::EOpTextureQueryLevels:
1757 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1758 default:
1759 assert(0);
1760 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001761 }
John Kessenich140f3df2015-06-26 16:58:36 -06001762 }
1763
Rex Xufc618912015-09-09 16:42:49 +08001764 // Check for image functions other than queries
1765 if (node->isImage()) {
1766 if (node->getOp() == glslang::EOpImageLoad) {
1767 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), arguments);
1768 }
1769 else if (node->getOp() == glslang::EOpImageStore) {
1770 builder.createNoResultOp(spv::OpImageWrite, arguments);
1771 return spv::NoResult;
1772 }
1773 else {
1774 // Process image atomic operations. GLSL "IMAGE_PARAMS" will involve in constructing an image texel
1775 // pointer and this pointer, as the first source operand, is required by SPIR-V atomic operations.
1776 std::vector<spv::Id> imageParams;
1777 auto opIt = arguments.begin();
1778 imageParams.push_back(*(opIt++));
1779 imageParams.push_back(*(opIt++));
1780 imageParams.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06001781
Rex Xufc618912015-09-09 16:42:49 +08001782 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
1783 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, imageParams);
1784
1785 std::vector<spv::Id> operands;
1786 operands.push_back(pointer);
1787 for (; opIt != arguments.end(); ++opIt)
1788 operands.push_back(*opIt);
1789
1790 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands);
1791 }
1792 }
1793
1794 // Check for texture functions other than queries
John Kessenichfc51d282015-08-19 13:34:18 -06001795 if (cracked.fetch)
1796 spv::MissingFunctionality("texel fetch");
1797 if (cracked.gather)
1798 spv::MissingFunctionality("texture gather");
1799
1800 // check for bias argument
1801 bool bias = false;
1802 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch) {
1803 int nonBiasArgCount = 2;
1804 if (cracked.offset)
1805 ++nonBiasArgCount;
1806 if (cracked.grad)
1807 nonBiasArgCount += 2;
1808
1809 if ((int)arguments.size() > nonBiasArgCount)
1810 bias = true;
1811 }
1812
1813 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1814
1815 // set the rest of the arguments
1816 params.coords = arguments[1];
1817 int extraArgs = 0;
1818 if (cubeCompare)
1819 params.Dref = arguments[2];
1820 else if (sampler.shadow) {
1821 std::vector<spv::Id> indexes;
1822 int comp;
1823 if (cracked.proj)
1824 comp = 3;
1825 else
1826 comp = builder.getNumComponents(params.coords) - 1;
1827 indexes.push_back(comp);
1828 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1829 }
1830 if (cracked.lod) {
1831 params.lod = arguments[2];
1832 ++extraArgs;
1833 }
1834 if (cracked.grad) {
1835 params.gradX = arguments[2 + extraArgs];
1836 params.gradY = arguments[3 + extraArgs];
1837 extraArgs += 2;
1838 }
1839 //if (gather && compare) {
1840 // params.compare = arguments[2 + extraArgs];
1841 // ++extraArgs;
1842 //}
1843 if (cracked.offset || cracked.offsets) {
1844 params.offset = arguments[2 + extraArgs];
1845 ++extraArgs;
1846 }
1847 if (bias) {
1848 params.bias = arguments[2 + extraArgs];
1849 ++extraArgs;
1850 }
1851
1852 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.proj, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001853}
1854
1855spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
1856{
1857 // Grab the function's pointer from the previously created function
1858 spv::Function* function = functionMap[node->getName().c_str()];
1859 if (! function)
1860 return 0;
1861
1862 const glslang::TIntermSequence& glslangArgs = node->getSequence();
1863 const glslang::TQualifierList& qualifiers = node->getQualifierList();
1864
1865 // See comments in makeFunctions() for details about the semantics for parameter passing.
1866 //
1867 // These imply we need a four step process:
1868 // 1. Evaluate the arguments
1869 // 2. Allocate and make copies of in, out, and inout arguments
1870 // 3. Make the call
1871 // 4. Copy back the results
1872
1873 // 1. Evaluate the arguments
1874 std::vector<spv::Builder::AccessChain> lValues;
1875 std::vector<spv::Id> rValues;
1876 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1877 // build l-value
1878 builder.clearAccessChain();
1879 glslangArgs[a]->traverse(this);
1880 // keep outputs as l-values, evaluate input-only as r-values
1881 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1882 // save l-value
1883 lValues.push_back(builder.getAccessChain());
1884 } else {
1885 // process r-value
1886 rValues.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangArgs[a]->getAsTyped()->getType())));
1887 }
1888 }
1889
1890 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
1891 // copy the original into that space.
1892 //
1893 // Also, build up the list of actual arguments to pass in for the call
1894 int lValueCount = 0;
1895 int rValueCount = 0;
1896 std::vector<spv::Id> spvArgs;
1897 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1898 spv::Id arg;
1899 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1900 // need space to hold the copy
1901 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
1902 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
1903 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
1904 // need to copy the input into output space
1905 builder.setAccessChain(lValues[lValueCount]);
1906 spv::Id copy = builder.accessChainLoad(spv::NoPrecision); // TODO: get precision
1907 builder.createStore(copy, arg);
1908 }
1909 ++lValueCount;
1910 } else {
1911 arg = rValues[rValueCount];
1912 ++rValueCount;
1913 }
1914 spvArgs.push_back(arg);
1915 }
1916
1917 // 3. Make the call.
1918 spv::Id result = builder.createFunctionCall(function, spvArgs);
1919
1920 // 4. Copy back out an "out" arguments.
1921 lValueCount = 0;
1922 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1923 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1924 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
1925 spv::Id copy = builder.createLoad(spvArgs[a]);
1926 builder.setAccessChain(lValues[lValueCount]);
1927 builder.accessChainStore(copy);
1928 }
1929 ++lValueCount;
1930 }
1931 }
1932
1933 return result;
1934}
1935
1936// Translate AST operation to SPV operation, already having SPV-based operands/types.
1937spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
1938 spv::Id typeId, spv::Id left, spv::Id right,
1939 glslang::TBasicType typeProxy, bool reduceComparison)
1940{
1941 bool isUnsigned = typeProxy == glslang::EbtUint;
1942 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
1943
1944 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06001945 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06001946 bool comparison = false;
1947
1948 switch (op) {
1949 case glslang::EOpAdd:
1950 case glslang::EOpAddAssign:
1951 if (isFloat)
1952 binOp = spv::OpFAdd;
1953 else
1954 binOp = spv::OpIAdd;
1955 break;
1956 case glslang::EOpSub:
1957 case glslang::EOpSubAssign:
1958 if (isFloat)
1959 binOp = spv::OpFSub;
1960 else
1961 binOp = spv::OpISub;
1962 break;
1963 case glslang::EOpMul:
1964 case glslang::EOpMulAssign:
1965 if (isFloat)
1966 binOp = spv::OpFMul;
1967 else
1968 binOp = spv::OpIMul;
1969 break;
1970 case glslang::EOpVectorTimesScalar:
1971 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06001972 if (isFloat) {
1973 if (builder.isVector(right))
1974 std::swap(left, right);
1975 assert(builder.isScalar(right));
1976 needMatchingVectors = false;
1977 binOp = spv::OpVectorTimesScalar;
1978 } else
1979 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06001980 break;
1981 case glslang::EOpVectorTimesMatrix:
1982 case glslang::EOpVectorTimesMatrixAssign:
1983 assert(builder.isVector(left));
1984 assert(builder.isMatrix(right));
1985 binOp = spv::OpVectorTimesMatrix;
1986 break;
1987 case glslang::EOpMatrixTimesVector:
1988 assert(builder.isMatrix(left));
1989 assert(builder.isVector(right));
1990 binOp = spv::OpMatrixTimesVector;
1991 break;
1992 case glslang::EOpMatrixTimesScalar:
1993 case glslang::EOpMatrixTimesScalarAssign:
1994 if (builder.isMatrix(right))
1995 std::swap(left, right);
1996 assert(builder.isScalar(right));
1997 binOp = spv::OpMatrixTimesScalar;
1998 break;
1999 case glslang::EOpMatrixTimesMatrix:
2000 case glslang::EOpMatrixTimesMatrixAssign:
2001 assert(builder.isMatrix(left));
2002 assert(builder.isMatrix(right));
2003 binOp = spv::OpMatrixTimesMatrix;
2004 break;
2005 case glslang::EOpOuterProduct:
2006 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002007 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002008 break;
2009
2010 case glslang::EOpDiv:
2011 case glslang::EOpDivAssign:
2012 if (isFloat)
2013 binOp = spv::OpFDiv;
2014 else if (isUnsigned)
2015 binOp = spv::OpUDiv;
2016 else
2017 binOp = spv::OpSDiv;
2018 break;
2019 case glslang::EOpMod:
2020 case glslang::EOpModAssign:
2021 if (isFloat)
2022 binOp = spv::OpFMod;
2023 else if (isUnsigned)
2024 binOp = spv::OpUMod;
2025 else
2026 binOp = spv::OpSMod;
2027 break;
2028 case glslang::EOpRightShift:
2029 case glslang::EOpRightShiftAssign:
2030 if (isUnsigned)
2031 binOp = spv::OpShiftRightLogical;
2032 else
2033 binOp = spv::OpShiftRightArithmetic;
2034 break;
2035 case glslang::EOpLeftShift:
2036 case glslang::EOpLeftShiftAssign:
2037 binOp = spv::OpShiftLeftLogical;
2038 break;
2039 case glslang::EOpAnd:
2040 case glslang::EOpAndAssign:
2041 binOp = spv::OpBitwiseAnd;
2042 break;
2043 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002044 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002045 binOp = spv::OpLogicalAnd;
2046 break;
2047 case glslang::EOpInclusiveOr:
2048 case glslang::EOpInclusiveOrAssign:
2049 binOp = spv::OpBitwiseOr;
2050 break;
2051 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002052 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002053 binOp = spv::OpLogicalOr;
2054 break;
2055 case glslang::EOpExclusiveOr:
2056 case glslang::EOpExclusiveOrAssign:
2057 binOp = spv::OpBitwiseXor;
2058 break;
2059 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002060 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002061 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002062 break;
2063
2064 case glslang::EOpLessThan:
2065 case glslang::EOpGreaterThan:
2066 case glslang::EOpLessThanEqual:
2067 case glslang::EOpGreaterThanEqual:
2068 case glslang::EOpEqual:
2069 case glslang::EOpNotEqual:
2070 case glslang::EOpVectorEqual:
2071 case glslang::EOpVectorNotEqual:
2072 comparison = true;
2073 break;
2074 default:
2075 break;
2076 }
2077
2078 if (binOp != spv::OpNop) {
2079 if (builder.isMatrix(left) || builder.isMatrix(right)) {
2080 switch (binOp) {
2081 case spv::OpMatrixTimesScalar:
2082 case spv::OpVectorTimesMatrix:
2083 case spv::OpMatrixTimesVector:
2084 case spv::OpMatrixTimesMatrix:
2085 break;
2086 case spv::OpFDiv:
2087 // turn it into a multiply...
2088 assert(builder.isMatrix(left) && builder.isScalar(right));
2089 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2090 binOp = spv::OpFMul;
2091 break;
2092 default:
2093 spv::MissingFunctionality("binary operation on matrix");
2094 break;
2095 }
2096
2097 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2098 builder.setPrecision(id, precision);
2099
2100 return id;
2101 }
2102
2103 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002104 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002105 builder.promoteScalar(precision, left, right);
2106
2107 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2108 builder.setPrecision(id, precision);
2109
2110 return id;
2111 }
2112
2113 if (! comparison)
2114 return 0;
2115
2116 // Comparison instructions
2117
2118 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2119 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2120
2121 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
2122 }
2123
2124 switch (op) {
2125 case glslang::EOpLessThan:
2126 if (isFloat)
2127 binOp = spv::OpFOrdLessThan;
2128 else if (isUnsigned)
2129 binOp = spv::OpULessThan;
2130 else
2131 binOp = spv::OpSLessThan;
2132 break;
2133 case glslang::EOpGreaterThan:
2134 if (isFloat)
2135 binOp = spv::OpFOrdGreaterThan;
2136 else if (isUnsigned)
2137 binOp = spv::OpUGreaterThan;
2138 else
2139 binOp = spv::OpSGreaterThan;
2140 break;
2141 case glslang::EOpLessThanEqual:
2142 if (isFloat)
2143 binOp = spv::OpFOrdLessThanEqual;
2144 else if (isUnsigned)
2145 binOp = spv::OpULessThanEqual;
2146 else
2147 binOp = spv::OpSLessThanEqual;
2148 break;
2149 case glslang::EOpGreaterThanEqual:
2150 if (isFloat)
2151 binOp = spv::OpFOrdGreaterThanEqual;
2152 else if (isUnsigned)
2153 binOp = spv::OpUGreaterThanEqual;
2154 else
2155 binOp = spv::OpSGreaterThanEqual;
2156 break;
2157 case glslang::EOpEqual:
2158 case glslang::EOpVectorEqual:
2159 if (isFloat)
2160 binOp = spv::OpFOrdEqual;
2161 else
2162 binOp = spv::OpIEqual;
2163 break;
2164 case glslang::EOpNotEqual:
2165 case glslang::EOpVectorNotEqual:
2166 if (isFloat)
2167 binOp = spv::OpFOrdNotEqual;
2168 else
2169 binOp = spv::OpINotEqual;
2170 break;
2171 default:
2172 break;
2173 }
2174
2175 if (binOp != spv::OpNop) {
2176 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2177 builder.setPrecision(id, precision);
2178
2179 return id;
2180 }
2181
2182 return 0;
2183}
2184
2185spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, bool isFloat)
2186{
2187 spv::Op unaryOp = spv::OpNop;
2188 int libCall = -1;
2189
2190 switch (op) {
2191 case glslang::EOpNegative:
2192 if (isFloat)
2193 unaryOp = spv::OpFNegate;
2194 else
2195 unaryOp = spv::OpSNegate;
2196 break;
2197
2198 case glslang::EOpLogicalNot:
2199 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002200 unaryOp = spv::OpLogicalNot;
2201 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002202 case glslang::EOpBitwiseNot:
2203 unaryOp = spv::OpNot;
2204 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002205
John Kessenich140f3df2015-06-26 16:58:36 -06002206 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002207 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002208 break;
2209 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002210 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002211 break;
2212 case glslang::EOpTranspose:
2213 unaryOp = spv::OpTranspose;
2214 break;
2215
2216 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002217 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002218 break;
2219 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002220 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002221 break;
2222 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002223 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002224 break;
2225 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002226 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002227 break;
2228 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002229 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002230 break;
2231 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002232 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002233 break;
2234 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002235 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002236 break;
2237 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002238 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002239 break;
2240
2241 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002242 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002243 break;
2244 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002245 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002246 break;
2247 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002248 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002249 break;
2250 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002251 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002252 break;
2253 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002254 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002255 break;
2256 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002257 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002258 break;
2259
2260 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002261 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002262 break;
2263 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002264 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002265 break;
2266
2267 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002268 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002269 break;
2270 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002271 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002272 break;
2273 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002274 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002275 break;
2276 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002277 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002278 break;
2279 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002280 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002281 break;
2282 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002283 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002284 break;
2285
2286 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002287 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002288 break;
2289 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002290 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002291 break;
2292 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002293 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002294 break;
2295 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002296 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002297 break;
2298 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002299 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002300 break;
2301 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002302 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002303 break;
2304
2305 case glslang::EOpIsNan:
2306 unaryOp = spv::OpIsNan;
2307 break;
2308 case glslang::EOpIsInf:
2309 unaryOp = spv::OpIsInf;
2310 break;
2311
John Kessenich140f3df2015-06-26 16:58:36 -06002312 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002313 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002314 break;
2315 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002316 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002317 break;
2318 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002319 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002320 break;
2321 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002322 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002323 break;
2324 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002325 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002326 break;
2327 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002328 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002329 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002330 case glslang::EOpPackSnorm4x8:
2331 libCall = spv::GLSLstd450PackSnorm4x8;
2332 break;
2333 case glslang::EOpUnpackSnorm4x8:
2334 libCall = spv::GLSLstd450UnpackSnorm4x8;
2335 break;
2336 case glslang::EOpPackUnorm4x8:
2337 libCall = spv::GLSLstd450PackUnorm4x8;
2338 break;
2339 case glslang::EOpUnpackUnorm4x8:
2340 libCall = spv::GLSLstd450UnpackUnorm4x8;
2341 break;
2342 case glslang::EOpPackDouble2x32:
2343 libCall = spv::GLSLstd450PackDouble2x32;
2344 break;
2345 case glslang::EOpUnpackDouble2x32:
2346 libCall = spv::GLSLstd450UnpackDouble2x32;
2347 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002348
2349 case glslang::EOpDPdx:
2350 unaryOp = spv::OpDPdx;
2351 break;
2352 case glslang::EOpDPdy:
2353 unaryOp = spv::OpDPdy;
2354 break;
2355 case glslang::EOpFwidth:
2356 unaryOp = spv::OpFwidth;
2357 break;
2358 case glslang::EOpDPdxFine:
2359 unaryOp = spv::OpDPdxFine;
2360 break;
2361 case glslang::EOpDPdyFine:
2362 unaryOp = spv::OpDPdyFine;
2363 break;
2364 case glslang::EOpFwidthFine:
2365 unaryOp = spv::OpFwidthFine;
2366 break;
2367 case glslang::EOpDPdxCoarse:
2368 unaryOp = spv::OpDPdxCoarse;
2369 break;
2370 case glslang::EOpDPdyCoarse:
2371 unaryOp = spv::OpDPdyCoarse;
2372 break;
2373 case glslang::EOpFwidthCoarse:
2374 unaryOp = spv::OpFwidthCoarse;
2375 break;
2376
2377 case glslang::EOpAny:
2378 unaryOp = spv::OpAny;
2379 break;
2380 case glslang::EOpAll:
2381 unaryOp = spv::OpAll;
2382 break;
2383
2384 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002385 if (isFloat)
2386 libCall = spv::GLSLstd450FAbs;
2387 else
2388 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002389 break;
2390 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002391 if (isFloat)
2392 libCall = spv::GLSLstd450FSign;
2393 else
2394 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002395 break;
2396
John Kessenichfc51d282015-08-19 13:34:18 -06002397 case glslang::EOpAtomicCounterIncrement:
2398 case glslang::EOpAtomicCounterDecrement:
2399 case glslang::EOpAtomicCounter:
2400 {
2401 // Handle all of the atomics in one place, in createAtomicOperation()
2402 std::vector<spv::Id> operands;
2403 operands.push_back(operand);
2404 return createAtomicOperation(op, precision, typeId, operands);
2405 }
2406
2407 case glslang::EOpImageLoad:
2408 unaryOp = spv::OpImageRead;
2409 break;
2410
2411 case glslang::EOpBitFieldReverse:
2412 unaryOp = spv::OpBitReverse;
2413 break;
2414 case glslang::EOpBitCount:
2415 unaryOp = spv::OpBitCount;
2416 break;
2417 case glslang::EOpFindLSB:
2418 libCall = spv::GLSLstd450FindILSB;
2419 break;
2420 case glslang::EOpFindMSB:
2421 spv::MissingFunctionality("signed vs. unsigned FindMSB");
2422 libCall = spv::GLSLstd450FindSMSB;
2423 break;
2424
John Kessenich140f3df2015-06-26 16:58:36 -06002425 default:
2426 return 0;
2427 }
2428
2429 spv::Id id;
2430 if (libCall >= 0) {
2431 std::vector<spv::Id> args;
2432 args.push_back(operand);
2433 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2434 } else
2435 id = builder.createUnaryOp(unaryOp, typeId, operand);
2436
2437 builder.setPrecision(id, precision);
2438
2439 return id;
2440}
2441
2442spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2443{
2444 spv::Op convOp = spv::OpNop;
2445 spv::Id zero = 0;
2446 spv::Id one = 0;
2447
2448 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2449
2450 switch (op) {
2451 case glslang::EOpConvIntToBool:
2452 case glslang::EOpConvUintToBool:
2453 zero = builder.makeUintConstant(0);
2454 zero = makeSmearedConstant(zero, vectorSize);
2455 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2456
2457 case glslang::EOpConvFloatToBool:
2458 zero = builder.makeFloatConstant(0.0F);
2459 zero = makeSmearedConstant(zero, vectorSize);
2460 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2461
2462 case glslang::EOpConvDoubleToBool:
2463 zero = builder.makeDoubleConstant(0.0);
2464 zero = makeSmearedConstant(zero, vectorSize);
2465 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2466
2467 case glslang::EOpConvBoolToFloat:
2468 convOp = spv::OpSelect;
2469 zero = builder.makeFloatConstant(0.0);
2470 one = builder.makeFloatConstant(1.0);
2471 break;
2472 case glslang::EOpConvBoolToDouble:
2473 convOp = spv::OpSelect;
2474 zero = builder.makeDoubleConstant(0.0);
2475 one = builder.makeDoubleConstant(1.0);
2476 break;
2477 case glslang::EOpConvBoolToInt:
2478 zero = builder.makeIntConstant(0);
2479 one = builder.makeIntConstant(1);
2480 convOp = spv::OpSelect;
2481 break;
2482 case glslang::EOpConvBoolToUint:
2483 zero = builder.makeUintConstant(0);
2484 one = builder.makeUintConstant(1);
2485 convOp = spv::OpSelect;
2486 break;
2487
2488 case glslang::EOpConvIntToFloat:
2489 case glslang::EOpConvIntToDouble:
2490 convOp = spv::OpConvertSToF;
2491 break;
2492
2493 case glslang::EOpConvUintToFloat:
2494 case glslang::EOpConvUintToDouble:
2495 convOp = spv::OpConvertUToF;
2496 break;
2497
2498 case glslang::EOpConvDoubleToFloat:
2499 case glslang::EOpConvFloatToDouble:
2500 convOp = spv::OpFConvert;
2501 break;
2502
2503 case glslang::EOpConvFloatToInt:
2504 case glslang::EOpConvDoubleToInt:
2505 convOp = spv::OpConvertFToS;
2506 break;
2507
2508 case glslang::EOpConvUintToInt:
2509 case glslang::EOpConvIntToUint:
2510 convOp = spv::OpBitcast;
2511 break;
2512
2513 case glslang::EOpConvFloatToUint:
2514 case glslang::EOpConvDoubleToUint:
2515 convOp = spv::OpConvertFToU;
2516 break;
2517 default:
2518 break;
2519 }
2520
2521 spv::Id result = 0;
2522 if (convOp == spv::OpNop)
2523 return result;
2524
2525 if (convOp == spv::OpSelect) {
2526 zero = makeSmearedConstant(zero, vectorSize);
2527 one = makeSmearedConstant(one, vectorSize);
2528 result = builder.createTriOp(convOp, destType, operand, one, zero);
2529 } else
2530 result = builder.createUnaryOp(convOp, destType, operand);
2531
2532 builder.setPrecision(result, precision);
2533
2534 return result;
2535}
2536
2537spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2538{
2539 if (vectorSize == 0)
2540 return constant;
2541
2542 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2543 std::vector<spv::Id> components;
2544 for (int c = 0; c < vectorSize; ++c)
2545 components.push_back(constant);
2546 return builder.makeCompositeConstant(vectorTypeId, components);
2547}
2548
John Kessenich426394d2015-07-23 10:22:48 -06002549// For glslang ops that map to SPV atomic opCodes
2550spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands)
2551{
2552 spv::Op opCode = spv::OpNop;
2553
2554 switch (op) {
2555 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08002556 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06002557 opCode = spv::OpAtomicIAdd;
2558 break;
2559 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08002560 case glslang::EOpImageAtomicMin:
2561 opCode = builder.isSignedType(typeId) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002562 break;
2563 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08002564 case glslang::EOpImageAtomicMax:
2565 opCode = builder.isSignedType(typeId) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002566 break;
2567 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08002568 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06002569 opCode = spv::OpAtomicAnd;
2570 break;
2571 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08002572 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06002573 opCode = spv::OpAtomicOr;
2574 break;
2575 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08002576 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06002577 opCode = spv::OpAtomicXor;
2578 break;
2579 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08002580 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06002581 opCode = spv::OpAtomicExchange;
2582 break;
2583 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08002584 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06002585 opCode = spv::OpAtomicCompareExchange;
2586 break;
2587 case glslang::EOpAtomicCounterIncrement:
2588 opCode = spv::OpAtomicIIncrement;
2589 break;
2590 case glslang::EOpAtomicCounterDecrement:
2591 opCode = spv::OpAtomicIDecrement;
2592 break;
2593 case glslang::EOpAtomicCounter:
2594 opCode = spv::OpAtomicLoad;
2595 break;
2596 default:
2597 spv::MissingFunctionality("missing nested atomic");
2598 break;
2599 }
2600
2601 // Sort out the operands
2602 // - mapping from glslang -> SPV
2603 // - there are extra SPV operands with no glslang source
2604 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2605 auto opIt = operands.begin(); // walk the glslang operands
2606 spvAtomicOperands.push_back(*(opIt++));
Rex Xud4782c12015-09-06 16:30:11 +08002607 spvAtomicOperands.push_back(spv::ScopeDevice); // TBD: what is the correct scope?
2608 spvAtomicOperands.push_back(spv::MemorySemanticsMaskNone); // TBD: what are the correct memory semantics?
John Kessenich426394d2015-07-23 10:22:48 -06002609
2610 // Add the rest of the operands, skipping the first one, which was dealt with above.
2611 // For some ops, there are none, for some 1, for compare-exchange, 2.
2612 for (; opIt != operands.end(); ++opIt)
2613 spvAtomicOperands.push_back(*opIt);
2614
2615 return builder.createOp(opCode, typeId, spvAtomicOperands);
2616}
2617
John Kessenich5e4b1242015-08-06 22:53:06 -06002618spv::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 -06002619{
John Kessenich5e4b1242015-08-06 22:53:06 -06002620 bool isUnsigned = typeProxy == glslang::EbtUint;
2621 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2622
John Kessenich140f3df2015-06-26 16:58:36 -06002623 spv::Op opCode = spv::OpNop;
2624 int libCall = -1;
2625
2626 switch (op) {
2627 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002628 if (isFloat)
2629 libCall = spv::GLSLstd450FMin;
2630 else if (isUnsigned)
2631 libCall = spv::GLSLstd450UMin;
2632 else
2633 libCall = spv::GLSLstd450SMin;
John Kessenich140f3df2015-06-26 16:58:36 -06002634 break;
2635 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002636 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002637 break;
2638 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002639 if (isFloat)
2640 libCall = spv::GLSLstd450FMax;
2641 else if (isUnsigned)
2642 libCall = spv::GLSLstd450UMax;
2643 else
2644 libCall = spv::GLSLstd450SMax;
John Kessenich140f3df2015-06-26 16:58:36 -06002645 break;
2646 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002647 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002648 break;
2649 case glslang::EOpDot:
2650 opCode = spv::OpDot;
2651 break;
2652 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002653 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002654 break;
2655
2656 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002657 if (isFloat)
2658 libCall = spv::GLSLstd450FClamp;
2659 else if (isUnsigned)
2660 libCall = spv::GLSLstd450UClamp;
2661 else
2662 libCall = spv::GLSLstd450SClamp;
John Kessenich140f3df2015-06-26 16:58:36 -06002663 break;
2664 case glslang::EOpMix:
John Kessenich5e4b1242015-08-06 22:53:06 -06002665 libCall = spv::GLSLstd450Mix;
John Kessenich140f3df2015-06-26 16:58:36 -06002666 break;
2667 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002668 libCall = spv::GLSLstd450Step;
John Kessenich140f3df2015-06-26 16:58:36 -06002669 break;
2670 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002671 libCall = spv::GLSLstd450SmoothStep;
John Kessenich140f3df2015-06-26 16:58:36 -06002672 break;
2673
2674 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002675 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002676 break;
2677 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002678 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002679 break;
2680 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002681 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002682 break;
2683 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002684 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002685 break;
2686 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002687 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002688 break;
John Kessenich426394d2015-07-23 10:22:48 -06002689
John Kessenich140f3df2015-06-26 16:58:36 -06002690 default:
2691 return 0;
2692 }
2693
2694 spv::Id id = 0;
2695 if (libCall >= 0)
2696 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, operands);
2697 else {
2698 switch (operands.size()) {
2699 case 0:
2700 // should all be handled by visitAggregate and createNoArgOperation
2701 assert(0);
2702 return 0;
2703 case 1:
2704 // should all be handled by createUnaryOperation
2705 assert(0);
2706 return 0;
2707 case 2:
2708 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
2709 break;
2710 case 3:
John Kessenich426394d2015-07-23 10:22:48 -06002711 id = builder.createTriOp(opCode, typeId, operands[0], operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002712 break;
2713 default:
2714 // These do not exist yet
2715 assert(0 && "operation with more than 3 operands");
2716 break;
2717 }
2718 }
2719
2720 builder.setPrecision(id, precision);
2721
2722 return id;
2723}
2724
2725// Intrinsics with no arguments, no return value, and no precision.
2726spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
2727{
2728 // TODO: get the barrier operands correct
2729
2730 switch (op) {
2731 case glslang::EOpEmitVertex:
2732 builder.createNoResultOp(spv::OpEmitVertex);
2733 return 0;
2734 case glslang::EOpEndPrimitive:
2735 builder.createNoResultOp(spv::OpEndPrimitive);
2736 return 0;
2737 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002738 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
2739 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06002740 return 0;
2741 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002742 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06002743 return 0;
2744 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06002745 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002746 return 0;
2747 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06002748 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002749 return 0;
2750 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06002751 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002752 return 0;
2753 case glslang::EOpMemoryBarrierShared:
John Kessenich5e4b1242015-08-06 22:53:06 -06002754 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupLocalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002755 return 0;
2756 case glslang::EOpGroupMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002757 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupGlobalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002758 return 0;
2759 default:
2760 spv::MissingFunctionality("operation with no arguments");
2761 return 0;
2762 }
2763}
2764
2765spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
2766{
John Kessenich2f273362015-07-18 22:34:27 -06002767 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06002768 spv::Id id;
2769 if (symbolValues.end() != iter) {
2770 id = iter->second;
2771 return id;
2772 }
2773
2774 // it was not found, create it
2775 id = createSpvVariable(symbol);
2776 symbolValues[symbol->getId()] = id;
2777
2778 if (! symbol->getType().isStruct()) {
2779 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
2780 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
2781 if (symbol->getQualifier().hasLocation())
2782 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
2783 if (symbol->getQualifier().hasIndex())
2784 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
2785 if (symbol->getQualifier().hasComponent())
2786 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
2787 if (glslangIntermediate->getXfbMode()) {
2788 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002789 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002790 if (symbol->getQualifier().hasXfbBuffer())
2791 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2792 if (symbol->getQualifier().hasXfbOffset())
2793 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
2794 }
2795 }
2796
2797 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
2798 if (symbol->getQualifier().hasStream())
2799 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
2800 if (symbol->getQualifier().hasSet())
2801 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
2802 if (symbol->getQualifier().hasBinding())
2803 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
2804 if (glslangIntermediate->getXfbMode()) {
2805 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002806 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002807 if (symbol->getQualifier().hasXfbBuffer())
2808 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2809 }
2810
2811 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06002812 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06002813 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06002814 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06002815
2816 if (linkageOnly)
2817 builder.addDecoration(id, spv::DecorationNoStaticUse);
2818
2819 return id;
2820}
2821
2822void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
2823{
2824 if (dec != spv::BadValue)
2825 builder.addDecoration(id, dec);
2826}
2827
2828void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
2829{
2830 if (dec != spv::BadValue)
2831 builder.addMemberDecoration(id, (unsigned)member, dec);
2832}
2833
2834// Use 'consts' as the flattened glslang source of scalar constants to recursively
2835// build the aggregate SPIR-V constant.
2836//
2837// If there are not enough elements present in 'consts', 0 will be substituted;
2838// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
2839//
2840spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst)
2841{
2842 // vector of constants for SPIR-V
2843 std::vector<spv::Id> spvConsts;
2844
2845 // Type is used for struct and array constants
2846 spv::Id typeId = convertGlslangToSpvType(glslangType);
2847
2848 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002849 glslang::TType elementType(glslangType, 0);
2850 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich140f3df2015-06-26 16:58:36 -06002851 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst));
2852 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002853 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06002854 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
2855 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst));
2856 } else if (glslangType.getStruct()) {
2857 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
2858 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
2859 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst));
2860 } else if (glslangType.isVector()) {
2861 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
2862 bool zero = nextConst >= consts.size();
2863 switch (glslangType.getBasicType()) {
2864 case glslang::EbtInt:
2865 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
2866 break;
2867 case glslang::EbtUint:
2868 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
2869 break;
2870 case glslang::EbtFloat:
2871 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
2872 break;
2873 case glslang::EbtDouble:
2874 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
2875 break;
2876 case glslang::EbtBool:
2877 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
2878 break;
2879 default:
2880 spv::MissingFunctionality("constant vector type");
2881 break;
2882 }
2883 ++nextConst;
2884 }
2885 } else {
2886 // we have a non-aggregate (scalar) constant
2887 bool zero = nextConst >= consts.size();
2888 spv::Id scalar = 0;
2889 switch (glslangType.getBasicType()) {
2890 case glslang::EbtInt:
2891 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst());
2892 break;
2893 case glslang::EbtUint:
2894 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst());
2895 break;
2896 case glslang::EbtFloat:
2897 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst());
2898 break;
2899 case glslang::EbtDouble:
2900 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst());
2901 break;
2902 case glslang::EbtBool:
2903 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst());
2904 break;
2905 default:
2906 spv::MissingFunctionality("constant scalar type");
2907 break;
2908 }
2909 ++nextConst;
2910 return scalar;
2911 }
2912
2913 return builder.makeCompositeConstant(typeId, spvConsts);
2914}
2915
2916}; // end anonymous namespace
2917
2918namespace glslang {
2919
John Kessenich68d78fd2015-07-12 19:28:10 -06002920void GetSpirvVersion(std::string& version)
2921{
John Kessenich9e55f632015-07-15 10:03:39 -06002922 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06002923 char buf[bufSize];
John Kessenich9e55f632015-07-15 10:03:39 -06002924 snprintf(buf, bufSize, "%d, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06002925 version = buf;
2926}
2927
John Kessenich140f3df2015-06-26 16:58:36 -06002928// Write SPIR-V out to a binary file
2929void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
2930{
2931 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06002932 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06002933 for (int i = 0; i < (int)spirv.size(); ++i) {
2934 unsigned int word = spirv[i];
2935 out.write((const char*)&word, 4);
2936 }
2937 out.close();
2938}
2939
2940//
2941// Set up the glslang traversal
2942//
2943void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
2944{
2945 TIntermNode* root = intermediate.getTreeRoot();
2946
2947 if (root == 0)
2948 return;
2949
2950 glslang::GetThreadPoolAllocator().push();
2951
2952 TGlslangToSpvTraverser it(&intermediate);
2953
2954 root->traverse(&it);
2955
2956 it.dumpSpv(spirv);
2957
2958 glslang::GetThreadPoolAllocator().pop();
2959}
2960
2961}; // end namespace glslang