blob: c1743757b24c63c49bf5d1af66e028a59f19437e [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
John Kessenich55e7d112015-11-15 21:33:39 -070063// For low-order part of the generator's magic number. Bump up
64// when there is a change in the style (e.g., if SSA form changes,
65// or a different instruction sequence to do something gets used).
66const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060067
68//
69// The main holder of information for translating glslang to SPIR-V.
70//
71// Derives from the AST walking base class.
72//
73class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
74public:
75 TGlslangToSpvTraverser(const glslang::TIntermediate*);
76 virtual ~TGlslangToSpvTraverser();
77
78 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
79 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
80 void visitConstantUnion(glslang::TIntermConstantUnion*);
81 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
82 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
83 void visitSymbol(glslang::TIntermSymbol* symbol);
84 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
85 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
86 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
87
John Kessenich7ba63412015-12-20 17:37:07 -070088 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -060089
90protected:
91 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
92 spv::Id getSampledType(const glslang::TSampler&);
93 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -070094 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenichf85e8062015-12-19 13:57:10 -070095 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -070096 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
97 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
98 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich140f3df2015-06-26 16:58:36 -060099
100 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
101 void makeFunctions(const glslang::TIntermSequence&);
102 void makeGlobalInitializers(const glslang::TIntermSequence&);
103 void visitFunctions(const glslang::TIntermSequence&);
104 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800105 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600106 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
107 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600108 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
109
110 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
John Kessenich04bb8a02015-12-12 12:28:14 -0700111 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800112 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -0700113 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600114 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
115 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800116 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600117 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 -0600118 spv::Id createNoArgOperation(glslang::TOperator op);
119 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
120 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700121 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600122 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700123 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
124 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600125 bool isTrivialLeaf(const glslang::TIntermTyped* node);
126 bool isTrivial(const glslang::TIntermTyped* node);
127 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600128
129 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700130 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600131 int sequenceDepth;
132
133 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
134 spv::Builder builder;
135 bool inMain;
136 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700137 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700138 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600139 const glslang::TIntermediate* glslangIntermediate;
140 spv::Id stdBuiltins;
141
John Kessenich2f273362015-07-18 22:34:27 -0600142 std::unordered_map<int, spv::Id> symbolValues;
143 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
144 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700145 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600146 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 -0600147 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600148};
149
150//
151// Helper functions for translating glslang representations to SPIR-V enumerants.
152//
153
154// Translate glslang profile to SPIR-V source language.
155spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
156{
157 switch (profile) {
158 case ENoProfile:
159 case ECoreProfile:
160 case ECompatibilityProfile:
161 return spv::SourceLanguageGLSL;
162 case EEsProfile:
163 return spv::SourceLanguageESSL;
164 default:
165 return spv::SourceLanguageUnknown;
166 }
167}
168
169// Translate glslang language (stage) to SPIR-V execution model.
170spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
171{
172 switch (stage) {
173 case EShLangVertex: return spv::ExecutionModelVertex;
174 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
175 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
176 case EShLangGeometry: return spv::ExecutionModelGeometry;
177 case EShLangFragment: return spv::ExecutionModelFragment;
178 case EShLangCompute: return spv::ExecutionModelGLCompute;
179 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700180 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600181 return spv::ExecutionModelFragment;
182 }
183}
184
185// Translate glslang type to SPIR-V storage class.
186spv::StorageClass TranslateStorageClass(const glslang::TType& type)
187{
188 if (type.getQualifier().isPipeInput())
189 return spv::StorageClassInput;
190 else if (type.getQualifier().isPipeOutput())
191 return spv::StorageClassOutput;
192 else if (type.getQualifier().isUniformOrBuffer()) {
193 if (type.getBasicType() == glslang::EbtBlock)
194 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800195 else if (type.getBasicType() == glslang::EbtAtomicUint)
196 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600197 else
198 return spv::StorageClassUniformConstant;
199 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
200 } else {
201 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700202 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
203 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600204 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
205 case glslang::EvqTemporary: return spv::StorageClassFunction;
206 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700207 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600208 return spv::StorageClassFunction;
209 }
210 }
211}
212
213// Translate glslang sampler type to SPIR-V dimensionality.
214spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
215{
216 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700217 case glslang::Esd1D: return spv::Dim1D;
218 case glslang::Esd2D: return spv::Dim2D;
219 case glslang::Esd3D: return spv::Dim3D;
220 case glslang::EsdCube: return spv::DimCube;
221 case glslang::EsdRect: return spv::DimRect;
222 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich140f3df2015-06-26 16:58:36 -0600223 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700224 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600225 return spv::Dim2D;
226 }
227}
228
229// Translate glslang type to SPIR-V precision decorations.
230spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
231{
232 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700233 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600234 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
235 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600236 default:
237 return spv::NoPrecision;
238 }
239}
240
241// Translate glslang type to SPIR-V block decorations.
242spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
243{
244 if (type.getBasicType() == glslang::EbtBlock) {
245 switch (type.getQualifier().storage) {
246 case glslang::EvqUniform: return spv::DecorationBlock;
247 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
248 case glslang::EvqVaryingIn: return spv::DecorationBlock;
249 case glslang::EvqVaryingOut: return spv::DecorationBlock;
250 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700251 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600252 break;
253 }
254 }
255
256 return (spv::Decoration)spv::BadValue;
257}
258
259// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700260spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600261{
262 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700263 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600264 case glslang::ElmRowMajor:
265 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700266 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600267 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700268 default:
269 // opaque layouts don't need a majorness
270 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600271 }
272 } else {
273 switch (type.getBasicType()) {
274 default:
275 return (spv::Decoration)spv::BadValue;
276 break;
277 case glslang::EbtBlock:
278 switch (type.getQualifier().storage) {
279 case glslang::EvqUniform:
280 case glslang::EvqBuffer:
281 switch (type.getQualifier().layoutPacking) {
282 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600283 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
284 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600285 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600286 }
287 case glslang::EvqVaryingIn:
288 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700289 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600290 return (spv::Decoration)spv::BadValue;
291 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700292 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600293 return (spv::Decoration)spv::BadValue;
294 }
295 }
296 }
297}
298
299// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700300// Returns spv::Decoration(spv::BadValue) when no decoration
301// should be applied.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700302spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600303{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700304 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700305 // Smooth decoration doesn't exist in SPIR-V 1.0
306 return (spv::Decoration)spv::BadValue;
307 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700308 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700309 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700310 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600311 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700312 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600313 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700314 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600315 return spv::DecorationCentroid;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700316 else if (qualifier.sample)
John Kessenich140f3df2015-06-26 16:58:36 -0600317 return spv::DecorationSample;
318 else
319 return (spv::Decoration)spv::BadValue;
320}
321
322// If glslang type is invaraiant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700323spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600324{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700325 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600326 return spv::DecorationInvariant;
327 else
328 return (spv::Decoration)spv::BadValue;
329}
330
331// Translate glslang built-in variable to SPIR-V built in decoration.
332spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
333{
334 switch (builtIn) {
335 case glslang::EbvPosition: return spv::BuiltInPosition;
336 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600337 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
338 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
339 case glslang::EbvVertexId: return spv::BuiltInVertexId;
340 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenichda581a22015-10-14 14:10:30 -0600341 case glslang::EbvBaseVertex:
342 case glslang::EbvBaseInstance:
343 case glslang::EbvDrawId:
344 // TODO: Add SPIR-V builtin ID.
345 spv::MissingFunctionality("Draw parameters");
346 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600347 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
348 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
349 case glslang::EbvLayer: return spv::BuiltInLayer;
350 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
351 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
352 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
353 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
354 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
355 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
356 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
357 case glslang::EbvFace: return spv::BuiltInFrontFacing;
358 case glslang::EbvSampleId: return spv::BuiltInSampleId;
359 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
360 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
John Kessenich140f3df2015-06-26 16:58:36 -0600361 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
362 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
363 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
364 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
365 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
366 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
367 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
368 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
369 default: return (spv::BuiltIn)spv::BadValue;
370 }
371}
372
Rex Xufc618912015-09-09 16:42:49 +0800373// Translate glslang image layout format to SPIR-V image format.
374spv::ImageFormat TranslateImageFormat(const glslang::TType& type)
375{
376 assert(type.getBasicType() == glslang::EbtSampler);
377
378 switch (type.getQualifier().layoutFormat) {
379 case glslang::ElfNone: return spv::ImageFormatUnknown;
380 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
381 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
382 case glslang::ElfR32f: return spv::ImageFormatR32f;
383 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
384 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
385 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
386 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
387 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
388 case glslang::ElfR16f: return spv::ImageFormatR16f;
389 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
390 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
391 case glslang::ElfRg16: return spv::ImageFormatRg16;
392 case glslang::ElfRg8: return spv::ImageFormatRg8;
393 case glslang::ElfR16: return spv::ImageFormatR16;
394 case glslang::ElfR8: return spv::ImageFormatR8;
395 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
396 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
397 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
398 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
399 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
400 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
401 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
402 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
403 case glslang::ElfR32i: return spv::ImageFormatR32i;
404 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
405 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
406 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
407 case glslang::ElfR16i: return spv::ImageFormatR16i;
408 case glslang::ElfR8i: return spv::ImageFormatR8i;
409 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
410 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
411 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
412 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
413 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
414 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
415 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
416 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
417 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
418 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
419 default: return (spv::ImageFormat)spv::BadValue;
420 }
421}
422
John Kesseniche0b6cad2015-12-24 10:30:13 -0700423void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
424{
425 if (child.layoutMatrix == glslang::ElmNone)
426 child.layoutMatrix = parent.layoutMatrix;
427
428 if (parent.invariant)
429 child.invariant = true;
430 if (parent.nopersp)
431 child.nopersp = true;
432 if (parent.flat)
433 child.flat = true;
434 if (parent.centroid)
435 child.centroid = true;
436 if (parent.patch)
437 child.patch = true;
438 if (parent.sample)
439 child.sample = true;
440}
441
442bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
443{
444 // This should list qualifiers that simultaneous satisify:
445 // - struct members can inherit from a struct declaration
446 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
447 // - are not part of the offset/st430/etc or row/column-major layout
448 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample;
449}
450
John Kessenich140f3df2015-06-26 16:58:36 -0600451//
452// Implement the TGlslangToSpvTraverser class.
453//
454
455TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
456 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700457 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600458 inMain(false), mainTerminated(false), linkageOnly(false),
459 glslangIntermediate(glslangIntermediate)
460{
461 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
462
463 builder.clearAccessChain();
464 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
465 stdBuiltins = builder.import("GLSL.std.450");
466 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
467 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700468 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600469
470 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600471 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
472 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600473 builder.addSourceExtension(it->c_str());
474
475 // Add the top-level modes for this shader.
476
477 if (glslangIntermediate->getXfbMode())
478 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
479
480 unsigned int mode;
481 switch (glslangIntermediate->getStage()) {
482 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600483 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600484 break;
485
486 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600487 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600488 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
489 break;
490
491 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600492 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600493 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700494 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
495 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
496 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600497 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600498 }
499 if (mode != spv::BadValue)
500 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
501
John Kesseniche6903322015-10-13 16:29:02 -0600502 switch (glslangIntermediate->getVertexSpacing()) {
503 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
504 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
505 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
506 default: mode = spv::BadValue; break;
507 }
508 if (mode != spv::BadValue)
509 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
510
511 switch (glslangIntermediate->getVertexOrder()) {
512 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
513 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
514 default: mode = spv::BadValue; break;
515 }
516 if (mode != spv::BadValue)
517 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
518
519 if (glslangIntermediate->getPointMode())
520 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600521 break;
522
523 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600524 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600525 switch (glslangIntermediate->getInputPrimitive()) {
526 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
527 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
528 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700529 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600530 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
531 default: mode = spv::BadValue; break;
532 }
533 if (mode != spv::BadValue)
534 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600535
John Kessenich140f3df2015-06-26 16:58:36 -0600536 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
537
538 switch (glslangIntermediate->getOutputPrimitive()) {
539 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
540 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
541 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
542 default: mode = spv::BadValue; break;
543 }
544 if (mode != spv::BadValue)
545 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
546 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
547 break;
548
549 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600550 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600551 if (glslangIntermediate->getPixelCenterInteger())
552 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600553
John Kessenich140f3df2015-06-26 16:58:36 -0600554 if (glslangIntermediate->getOriginUpperLeft())
555 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600556 else
557 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600558
559 if (glslangIntermediate->getEarlyFragmentTests())
560 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
561
562 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600563 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
564 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
565 default: mode = spv::BadValue; break;
566 }
567 if (mode != spv::BadValue)
568 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
569
570 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
571 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600572 break;
573
574 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600575 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600576 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
577 glslangIntermediate->getLocalSize(1),
578 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600579 break;
580
581 default:
582 break;
583 }
584
585}
586
John Kessenich7ba63412015-12-20 17:37:07 -0700587// Finish everything and dump
588void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
589{
590 // finish off the entry-point SPV instruction by adding the Input/Output <id>
591 for (auto it : iOSet)
592 entryPoint->addIdOperand(it);
593
594 builder.dump(out);
595}
596
John Kessenich140f3df2015-06-26 16:58:36 -0600597TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
598{
599 if (! mainTerminated) {
600 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
601 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600602 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600603 }
604}
605
606//
607// Implement the traversal functions.
608//
609// Return true from interior nodes to have the external traversal
610// continue on to children. Return false if children were
611// already processed.
612//
613
614//
615// Symbols can turn into
616// - uniform/input reads
617// - output writes
618// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
619// - something simple that degenerates into the last bullet
620//
621void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
622{
623 // getSymbolId() will set up all the IO decorations on the first call.
624 // Formal function parameters were mapped during makeFunctions().
625 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700626
627 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
628 if (builder.isPointer(id)) {
629 spv::StorageClass sc = builder.getStorageClass(id);
630 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
631 iOSet.insert(id);
632 }
633
634 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich140f3df2015-06-26 16:58:36 -0600635 if (! linkageOnly) {
636 // Prepare to generate code for the access
637
638 // L-value chains will be computed left to right. We're on the symbol now,
639 // which is the left-most part of the access chain, so now is "clear" time,
640 // followed by setting the base.
641 builder.clearAccessChain();
642
643 // For now, we consider all user variables as being in memory, so they are pointers,
644 // except for "const in" arguments to a function, which are an intermediate object.
645 // See comments in handleUserFunctionCall().
646 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
647 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
648 builder.setAccessChainRValue(id);
649 else
650 builder.setAccessChainLValue(id);
651 }
652}
653
654bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
655{
656 // First, handle special cases
657 switch (node->getOp()) {
658 case glslang::EOpAssign:
659 case glslang::EOpAddAssign:
660 case glslang::EOpSubAssign:
661 case glslang::EOpMulAssign:
662 case glslang::EOpVectorTimesMatrixAssign:
663 case glslang::EOpVectorTimesScalarAssign:
664 case glslang::EOpMatrixTimesScalarAssign:
665 case glslang::EOpMatrixTimesMatrixAssign:
666 case glslang::EOpDivAssign:
667 case glslang::EOpModAssign:
668 case glslang::EOpAndAssign:
669 case glslang::EOpInclusiveOrAssign:
670 case glslang::EOpExclusiveOrAssign:
671 case glslang::EOpLeftShiftAssign:
672 case glslang::EOpRightShiftAssign:
673 // A bin-op assign "a += b" means the same thing as "a = a + b"
674 // where a is evaluated before b. For a simple assignment, GLSL
675 // says to evaluate the left before the right. So, always, left
676 // node then right node.
677 {
678 // get the left l-value, save it away
679 builder.clearAccessChain();
680 node->getLeft()->traverse(this);
681 spv::Builder::AccessChain lValue = builder.getAccessChain();
682
683 // evaluate the right
684 builder.clearAccessChain();
685 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600686 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600687
688 if (node->getOp() != glslang::EOpAssign) {
689 // the left is also an r-value
690 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600691 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600692
693 // do the operation
694 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
695 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
696 node->getType().getBasicType());
697
698 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700699 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600700 }
701
702 // store the result
703 builder.setAccessChain(lValue);
704 builder.accessChainStore(rValue);
705
706 // assignments are expressions having an rValue after they are evaluated...
707 builder.clearAccessChain();
708 builder.setAccessChainRValue(rValue);
709 }
710 return false;
711 case glslang::EOpIndexDirect:
712 case glslang::EOpIndexDirectStruct:
713 {
714 // Get the left part of the access chain.
715 node->getLeft()->traverse(this);
716
717 // Add the next element in the chain
718
John Kessenich55e7d112015-11-15 21:33:39 -0700719 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600720 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
721 // This may be, e.g., an anonymous block-member selection, which generally need
722 // index remapping due to hidden members in anonymous blocks.
723 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700724 assert(remapper.size() > 0);
725 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600726 }
727
728 if (! node->getLeft()->getType().isArray() &&
729 node->getLeft()->getType().isVector() &&
730 node->getOp() == glslang::EOpIndexDirect) {
731 // This is essentially a hard-coded vector swizzle of size 1,
732 // so short circuit the access-chain stuff with a swizzle.
733 std::vector<unsigned> swizzle;
734 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600735 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600736 } else {
737 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600738 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600739 }
740 }
741 return false;
742 case glslang::EOpIndexIndirect:
743 {
744 // Structure or array or vector indirection.
745 // Will use native SPIR-V access-chain for struct and array indirection;
746 // matrices are arrays of vectors, so will also work for a matrix.
747 // Will use the access chain's 'component' for variable index into a vector.
748
749 // This adapter is building access chains left to right.
750 // Set up the access chain to the left.
751 node->getLeft()->traverse(this);
752
753 // save it so that computing the right side doesn't trash it
754 spv::Builder::AccessChain partial = builder.getAccessChain();
755
756 // compute the next index in the chain
757 builder.clearAccessChain();
758 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600759 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600760
761 // restore the saved access chain
762 builder.setAccessChain(partial);
763
764 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600765 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600766 else
John Kessenichfa668da2015-09-13 14:46:30 -0600767 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600768 }
769 return false;
770 case glslang::EOpVectorSwizzle:
771 {
772 node->getLeft()->traverse(this);
773 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
774 std::vector<unsigned> swizzle;
775 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
776 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600777 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600778 }
779 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600780 case glslang::EOpLogicalOr:
781 case glslang::EOpLogicalAnd:
782 {
783
784 // These may require short circuiting, but can sometimes be done as straight
785 // binary operations. The right operand must be short circuited if it has
786 // side effects, and should probably be if it is complex.
787 if (isTrivial(node->getRight()->getAsTyped()))
788 break; // handle below as a normal binary operation
789 // otherwise, we need to do dynamic short circuiting on the right operand
790 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
791 builder.clearAccessChain();
792 builder.setAccessChainRValue(result);
793 }
794 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600795 default:
796 break;
797 }
798
799 // Assume generic binary op...
800
801 // Get the operands
802 builder.clearAccessChain();
803 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600804 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600805
806 builder.clearAccessChain();
807 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600808 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600809
810 spv::Id result;
811 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
812
813 result = createBinaryOperation(node->getOp(), precision,
814 convertGlslangToSpvType(node->getType()), left, right,
815 node->getLeft()->getType().getBasicType());
816
John Kessenich50e57562015-12-21 21:21:11 -0700817 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600818 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700819 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700820 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600821 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600822 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600823 return false;
824 }
John Kessenich140f3df2015-06-26 16:58:36 -0600825}
826
827bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
828{
John Kessenichfc51d282015-08-19 13:34:18 -0600829 spv::Id result = spv::NoResult;
830
831 // try texturing first
832 result = createImageTextureFunctionCall(node);
833 if (result != spv::NoResult) {
834 builder.clearAccessChain();
835 builder.setAccessChainRValue(result);
836
837 return false; // done with this node
838 }
839
840 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600841
842 if (node->getOp() == glslang::EOpArrayLength) {
843 // Quite special; won't want to evaluate the operand.
844
845 // Normal .length() would have been constant folded by the front-end.
846 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600847 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600848 assert(node->getOperand()->getType().isRuntimeSizedArray());
849 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
850 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600851 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
852 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600853
854 builder.clearAccessChain();
855 builder.setAccessChainRValue(length);
856
857 return false;
858 }
859
John Kessenichfc51d282015-08-19 13:34:18 -0600860 // Start by evaluating the operand
861
John Kessenich140f3df2015-06-26 16:58:36 -0600862 builder.clearAccessChain();
863 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800864
Rex Xufc618912015-09-09 16:42:49 +0800865 spv::Id operand = spv::NoResult;
866
867 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
868 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800869 node->getOp() == glslang::EOpAtomicCounter ||
870 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800871 operand = builder.accessChainGetLValue(); // Special case l-value operands
872 else
Rex Xu30f92582015-09-14 10:38:56 +0800873 operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600874
875 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
876
877 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600878 if (! result)
879 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600880
881 // if not, then possibly an operation
882 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700883 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600884
885 if (result) {
886 builder.clearAccessChain();
887 builder.setAccessChainRValue(result);
888
889 return false; // done with this node
890 }
891
892 // it must be a special case, check...
893 switch (node->getOp()) {
894 case glslang::EOpPostIncrement:
895 case glslang::EOpPostDecrement:
896 case glslang::EOpPreIncrement:
897 case glslang::EOpPreDecrement:
898 {
899 // we need the integer value "1" or the floating point "1.0" to add/subtract
900 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
901 builder.makeFloatConstant(1.0F) :
902 builder.makeIntConstant(1);
903 glslang::TOperator op;
904 if (node->getOp() == glslang::EOpPreIncrement ||
905 node->getOp() == glslang::EOpPostIncrement)
906 op = glslang::EOpAdd;
907 else
908 op = glslang::EOpSub;
909
910 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
911 convertGlslangToSpvType(node->getType()), operand, one,
912 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -0700913 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600914
915 // The result of operation is always stored, but conditionally the
916 // consumed result. The consumed result is always an r-value.
917 builder.accessChainStore(result);
918 builder.clearAccessChain();
919 if (node->getOp() == glslang::EOpPreIncrement ||
920 node->getOp() == glslang::EOpPreDecrement)
921 builder.setAccessChainRValue(result);
922 else
923 builder.setAccessChainRValue(operand);
924 }
925
926 return false;
927
928 case glslang::EOpEmitStreamVertex:
929 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
930 return false;
931 case glslang::EOpEndStreamPrimitive:
932 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
933 return false;
934
935 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700936 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -0700937 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -0600938 }
John Kessenich140f3df2015-06-26 16:58:36 -0600939}
940
941bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
942{
John Kessenichfc51d282015-08-19 13:34:18 -0600943 spv::Id result = spv::NoResult;
944
945 // try texturing
946 result = createImageTextureFunctionCall(node);
947 if (result != spv::NoResult) {
948 builder.clearAccessChain();
949 builder.setAccessChainRValue(result);
950
951 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600952 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800953 // "imageStore" is a special case, which has no result
954 return false;
955 }
John Kessenichfc51d282015-08-19 13:34:18 -0600956
John Kessenich140f3df2015-06-26 16:58:36 -0600957 glslang::TOperator binOp = glslang::EOpNull;
958 bool reduceComparison = true;
959 bool isMatrix = false;
960 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600961 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600962
963 assert(node->getOp());
964
965 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
966
967 switch (node->getOp()) {
968 case glslang::EOpSequence:
969 {
970 if (preVisit)
971 ++sequenceDepth;
972 else
973 --sequenceDepth;
974
975 if (sequenceDepth == 1) {
976 // If this is the parent node of all the functions, we want to see them
977 // early, so all call points have actual SPIR-V functions to reference.
978 // In all cases, still let the traverser visit the children for us.
979 makeFunctions(node->getAsAggregate()->getSequence());
980
981 // Also, we want all globals initializers to go into the entry of main(), before
982 // anything else gets there, so visit out of order, doing them all now.
983 makeGlobalInitializers(node->getAsAggregate()->getSequence());
984
985 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
986 // so do them manually.
987 visitFunctions(node->getAsAggregate()->getSequence());
988
989 return false;
990 }
991
992 return true;
993 }
994 case glslang::EOpLinkerObjects:
995 {
996 if (visit == glslang::EvPreVisit)
997 linkageOnly = true;
998 else
999 linkageOnly = false;
1000
1001 return true;
1002 }
1003 case glslang::EOpComma:
1004 {
1005 // processing from left to right naturally leaves the right-most
1006 // lying around in the access chain
1007 glslang::TIntermSequence& glslangOperands = node->getSequence();
1008 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1009 glslangOperands[i]->traverse(this);
1010
1011 return false;
1012 }
1013 case glslang::EOpFunction:
1014 if (visit == glslang::EvPreVisit) {
1015 if (isShaderEntrypoint(node)) {
1016 inMain = true;
1017 builder.setBuildPoint(shaderEntry->getLastBlock());
1018 } else {
1019 handleFunctionEntry(node);
1020 }
1021 } else {
1022 if (inMain)
1023 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001024 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001025 inMain = false;
1026 }
1027
1028 return true;
1029 case glslang::EOpParameters:
1030 // Parameters will have been consumed by EOpFunction processing, but not
1031 // the body, so we still visited the function node's children, making this
1032 // child redundant.
1033 return false;
1034 case glslang::EOpFunctionCall:
1035 {
1036 if (node->isUserDefined())
1037 result = handleUserFunctionCall(node);
John Kessenich55e7d112015-11-15 21:33:39 -07001038 assert(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001039 builder.clearAccessChain();
1040 builder.setAccessChainRValue(result);
1041
1042 return false;
1043 }
1044 case glslang::EOpConstructMat2x2:
1045 case glslang::EOpConstructMat2x3:
1046 case glslang::EOpConstructMat2x4:
1047 case glslang::EOpConstructMat3x2:
1048 case glslang::EOpConstructMat3x3:
1049 case glslang::EOpConstructMat3x4:
1050 case glslang::EOpConstructMat4x2:
1051 case glslang::EOpConstructMat4x3:
1052 case glslang::EOpConstructMat4x4:
1053 case glslang::EOpConstructDMat2x2:
1054 case glslang::EOpConstructDMat2x3:
1055 case glslang::EOpConstructDMat2x4:
1056 case glslang::EOpConstructDMat3x2:
1057 case glslang::EOpConstructDMat3x3:
1058 case glslang::EOpConstructDMat3x4:
1059 case glslang::EOpConstructDMat4x2:
1060 case glslang::EOpConstructDMat4x3:
1061 case glslang::EOpConstructDMat4x4:
1062 isMatrix = true;
1063 // fall through
1064 case glslang::EOpConstructFloat:
1065 case glslang::EOpConstructVec2:
1066 case glslang::EOpConstructVec3:
1067 case glslang::EOpConstructVec4:
1068 case glslang::EOpConstructDouble:
1069 case glslang::EOpConstructDVec2:
1070 case glslang::EOpConstructDVec3:
1071 case glslang::EOpConstructDVec4:
1072 case glslang::EOpConstructBool:
1073 case glslang::EOpConstructBVec2:
1074 case glslang::EOpConstructBVec3:
1075 case glslang::EOpConstructBVec4:
1076 case glslang::EOpConstructInt:
1077 case glslang::EOpConstructIVec2:
1078 case glslang::EOpConstructIVec3:
1079 case glslang::EOpConstructIVec4:
1080 case glslang::EOpConstructUint:
1081 case glslang::EOpConstructUVec2:
1082 case glslang::EOpConstructUVec3:
1083 case glslang::EOpConstructUVec4:
1084 case glslang::EOpConstructStruct:
1085 {
1086 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001087 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001088 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1089 spv::Id constructed;
1090 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1091 std::vector<spv::Id> constituents;
1092 for (int c = 0; c < (int)arguments.size(); ++c)
1093 constituents.push_back(arguments[c]);
1094 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001095 } else if (isMatrix)
1096 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1097 else
1098 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001099
1100 builder.clearAccessChain();
1101 builder.setAccessChainRValue(constructed);
1102
1103 return false;
1104 }
1105
1106 // These six are component-wise compares with component-wise results.
1107 // Forward on to createBinaryOperation(), requesting a vector result.
1108 case glslang::EOpLessThan:
1109 case glslang::EOpGreaterThan:
1110 case glslang::EOpLessThanEqual:
1111 case glslang::EOpGreaterThanEqual:
1112 case glslang::EOpVectorEqual:
1113 case glslang::EOpVectorNotEqual:
1114 {
1115 // Map the operation to a binary
1116 binOp = node->getOp();
1117 reduceComparison = false;
1118 switch (node->getOp()) {
1119 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1120 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1121 default: binOp = node->getOp(); break;
1122 }
1123
1124 break;
1125 }
1126 case glslang::EOpMul:
1127 // compontent-wise matrix multiply
1128 binOp = glslang::EOpMul;
1129 break;
1130 case glslang::EOpOuterProduct:
1131 // two vectors multiplied to make a matrix
1132 binOp = glslang::EOpOuterProduct;
1133 break;
1134 case glslang::EOpDot:
1135 {
1136 // for scalar dot product, use multiply
1137 glslang::TIntermSequence& glslangOperands = node->getSequence();
1138 if (! glslangOperands[0]->getAsTyped()->isVector())
1139 binOp = glslang::EOpMul;
1140 break;
1141 }
1142 case glslang::EOpMod:
1143 // when an aggregate, this is the floating-point mod built-in function,
1144 // which can be emitted by the one in createBinaryOperation()
1145 binOp = glslang::EOpMod;
1146 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001147 case glslang::EOpEmitVertex:
1148 case glslang::EOpEndPrimitive:
1149 case glslang::EOpBarrier:
1150 case glslang::EOpMemoryBarrier:
1151 case glslang::EOpMemoryBarrierAtomicCounter:
1152 case glslang::EOpMemoryBarrierBuffer:
1153 case glslang::EOpMemoryBarrierImage:
1154 case glslang::EOpMemoryBarrierShared:
1155 case glslang::EOpGroupMemoryBarrier:
1156 noReturnValue = true;
1157 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1158 break;
1159
John Kessenich426394d2015-07-23 10:22:48 -06001160 case glslang::EOpAtomicAdd:
1161 case glslang::EOpAtomicMin:
1162 case glslang::EOpAtomicMax:
1163 case glslang::EOpAtomicAnd:
1164 case glslang::EOpAtomicOr:
1165 case glslang::EOpAtomicXor:
1166 case glslang::EOpAtomicExchange:
1167 case glslang::EOpAtomicCompSwap:
1168 atomic = true;
1169 break;
1170
John Kessenich140f3df2015-06-26 16:58:36 -06001171 default:
1172 break;
1173 }
1174
1175 //
1176 // See if it maps to a regular operation.
1177 //
John Kessenich140f3df2015-06-26 16:58:36 -06001178 if (binOp != glslang::EOpNull) {
1179 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1180 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1181 assert(left && right);
1182
1183 builder.clearAccessChain();
1184 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001185 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001186
1187 builder.clearAccessChain();
1188 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001189 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001190
1191 result = createBinaryOperation(binOp, precision,
1192 convertGlslangToSpvType(node->getType()), leftId, rightId,
1193 left->getType().getBasicType(), reduceComparison);
1194
1195 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001196 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001197 builder.clearAccessChain();
1198 builder.setAccessChainRValue(result);
1199
1200 return false;
1201 }
1202
John Kessenich426394d2015-07-23 10:22:48 -06001203 //
1204 // Create the list of operands.
1205 //
John Kessenich140f3df2015-06-26 16:58:36 -06001206 glslang::TIntermSequence& glslangOperands = node->getSequence();
1207 std::vector<spv::Id> operands;
1208 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1209 builder.clearAccessChain();
1210 glslangOperands[arg]->traverse(this);
1211
1212 // special case l-value operands; there are just a few
1213 bool lvalue = false;
1214 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001215 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001216 case glslang::EOpModf:
1217 if (arg == 1)
1218 lvalue = true;
1219 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001220 case glslang::EOpInterpolateAtSample:
1221 case glslang::EOpInterpolateAtOffset:
1222 if (arg == 0)
1223 lvalue = true;
1224 break;
Rex Xud4782c12015-09-06 16:30:11 +08001225 case glslang::EOpAtomicAdd:
1226 case glslang::EOpAtomicMin:
1227 case glslang::EOpAtomicMax:
1228 case glslang::EOpAtomicAnd:
1229 case glslang::EOpAtomicOr:
1230 case glslang::EOpAtomicXor:
1231 case glslang::EOpAtomicExchange:
1232 case glslang::EOpAtomicCompSwap:
1233 if (arg == 0)
1234 lvalue = true;
1235 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001236 case glslang::EOpAddCarry:
1237 case glslang::EOpSubBorrow:
1238 if (arg == 2)
1239 lvalue = true;
1240 break;
1241 case glslang::EOpUMulExtended:
1242 case glslang::EOpIMulExtended:
1243 if (arg >= 2)
1244 lvalue = true;
1245 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001246 default:
1247 break;
1248 }
1249 if (lvalue)
1250 operands.push_back(builder.accessChainGetLValue());
1251 else
John Kessenichfa668da2015-09-13 14:46:30 -06001252 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001253 }
John Kessenich426394d2015-07-23 10:22:48 -06001254
1255 if (atomic) {
1256 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001257 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001258 } else {
1259 // Pass through to generic operations.
1260 switch (glslangOperands.size()) {
1261 case 0:
1262 result = createNoArgOperation(node->getOp());
1263 break;
1264 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001265 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001266 break;
1267 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001268 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001269 break;
1270 }
John Kessenich140f3df2015-06-26 16:58:36 -06001271 }
1272
1273 if (noReturnValue)
1274 return false;
1275
1276 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001277 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001278 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001279 } else {
1280 builder.clearAccessChain();
1281 builder.setAccessChainRValue(result);
1282 return false;
1283 }
1284}
1285
1286bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1287{
1288 // This path handles both if-then-else and ?:
1289 // The if-then-else has a node type of void, while
1290 // ?: has a non-void node type
1291 spv::Id result = 0;
1292 if (node->getBasicType() != glslang::EbtVoid) {
1293 // don't handle this as just on-the-fly temporaries, because there will be two names
1294 // and better to leave SSA to later passes
1295 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1296 }
1297
1298 // emit the condition before doing anything with selection
1299 node->getCondition()->traverse(this);
1300
1301 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001302 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001303
1304 if (node->getTrueBlock()) {
1305 // emit the "then" statement
1306 node->getTrueBlock()->traverse(this);
1307 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001308 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001309 }
1310
1311 if (node->getFalseBlock()) {
1312 ifBuilder.makeBeginElse();
1313 // emit the "else" statement
1314 node->getFalseBlock()->traverse(this);
1315 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001316 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001317 }
1318
1319 ifBuilder.makeEndIf();
1320
1321 if (result) {
1322 // GLSL only has r-values as the result of a :?, but
1323 // if we have an l-value, that can be more efficient if it will
1324 // become the base of a complex r-value expression, because the
1325 // next layer copies r-values into memory to use the access-chain mechanism
1326 builder.clearAccessChain();
1327 builder.setAccessChainLValue(result);
1328 }
1329
1330 return false;
1331}
1332
1333bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1334{
1335 // emit and get the condition before doing anything with switch
1336 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001337 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001338
1339 // browse the children to sort out code segments
1340 int defaultSegment = -1;
1341 std::vector<TIntermNode*> codeSegments;
1342 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1343 std::vector<int> caseValues;
1344 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1345 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1346 TIntermNode* child = *c;
1347 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001348 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001349 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001350 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001351 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1352 } else
1353 codeSegments.push_back(child);
1354 }
1355
1356 // handle the case where the last code segment is missing, due to no code
1357 // statements between the last case and the end of the switch statement
1358 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1359 (int)codeSegments.size() == defaultSegment)
1360 codeSegments.push_back(nullptr);
1361
1362 // make the switch statement
1363 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001364 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001365
1366 // emit all the code in the segments
1367 breakForLoop.push(false);
1368 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1369 builder.nextSwitchSegment(segmentBlocks, s);
1370 if (codeSegments[s])
1371 codeSegments[s]->traverse(this);
1372 else
1373 builder.addSwitchBreak();
1374 }
1375 breakForLoop.pop();
1376
1377 builder.endSwitch(segmentBlocks);
1378
1379 return false;
1380}
1381
1382void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1383{
1384 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001385 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001386
1387 builder.clearAccessChain();
1388 builder.setAccessChainRValue(constant);
1389}
1390
1391bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1392{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001393 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001394 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001395 // Spec requires back edges to target header blocks, and every header block
1396 // must dominate its merge block. Make a header block first to ensure these
1397 // conditions are met. By definition, it will contain OpLoopMerge, followed
1398 // by a block-ending branch. But we don't want to put any other body/test
1399 // instructions in it, since the body/test may have arbitrary instructions,
1400 // including merges of its own.
1401 builder.setBuildPoint(&blocks.head);
1402 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001403 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001404 spv::Block& test = builder.makeNewBlock();
1405 builder.createBranch(&test);
1406
1407 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001408 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001409 spv::Id condition =
1410 builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001411 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1412
1413 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001414 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001415 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001416 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001417 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001418 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001419
1420 builder.setBuildPoint(&blocks.continue_target);
1421 if (node->getTerminal())
1422 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001423 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001424 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001425 builder.createBranch(&blocks.body);
1426
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001427 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001428 builder.setBuildPoint(&blocks.body);
1429 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001430 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001431 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001432 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001433
1434 builder.setBuildPoint(&blocks.continue_target);
1435 if (node->getTerminal())
1436 node->getTerminal()->traverse(this);
1437 if (node->getTest()) {
1438 node->getTest()->traverse(this);
1439 spv::Id condition =
1440 builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001441 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001442 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001443 // TODO: unless there was a break/return/discard instruction
1444 // somewhere in the body, this is an infinite loop, so we should
1445 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001446 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001447 }
John Kessenich140f3df2015-06-26 16:58:36 -06001448 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001449 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001450 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001451 return false;
1452}
1453
1454bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1455{
1456 if (node->getExpression())
1457 node->getExpression()->traverse(this);
1458
1459 switch (node->getFlowOp()) {
1460 case glslang::EOpKill:
1461 builder.makeDiscard();
1462 break;
1463 case glslang::EOpBreak:
1464 if (breakForLoop.top())
1465 builder.createLoopExit();
1466 else
1467 builder.addSwitchBreak();
1468 break;
1469 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001470 builder.createLoopContinue();
1471 break;
1472 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001473 if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001474 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001475 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001476 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001477
1478 builder.clearAccessChain();
1479 break;
1480
1481 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001482 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001483 break;
1484 }
1485
1486 return false;
1487}
1488
1489spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1490{
1491 // First, steer off constants, which are not SPIR-V variables, but
1492 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001493 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001494 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001495 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001496 }
1497
1498 // Now, handle actual variables
1499 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1500 spv::Id spvType = convertGlslangToSpvType(node->getType());
1501
1502 const char* name = node->getName().c_str();
1503 if (glslang::IsAnonymous(name))
1504 name = "";
1505
1506 return builder.createVariable(storageClass, spvType, name);
1507}
1508
1509// Return type Id of the sampled type.
1510spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1511{
1512 switch (sampler.type) {
1513 case glslang::EbtFloat: return builder.makeFloatType(32);
1514 case glslang::EbtInt: return builder.makeIntType(32);
1515 case glslang::EbtUint: return builder.makeUintType(32);
1516 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001517 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001518 return builder.makeFloatType(32);
1519 }
1520}
1521
John Kessenich3ac051e2015-12-20 11:29:16 -07001522// Convert from a glslang type to an SPV type, by calling into a
1523// recursive version of this function. This establishes the inherited
1524// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001525spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1526{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001527 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001528}
1529
1530// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1531// explicitLayout can be kept the same throughout the heirarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001532spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001533{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001534 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001535
1536 switch (type.getBasicType()) {
1537 case glslang::EbtVoid:
1538 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001539 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001540 break;
1541 case glslang::EbtFloat:
1542 spvType = builder.makeFloatType(32);
1543 break;
1544 case glslang::EbtDouble:
1545 spvType = builder.makeFloatType(64);
1546 break;
1547 case glslang::EbtBool:
1548 spvType = builder.makeBoolType();
1549 break;
1550 case glslang::EbtInt:
1551 spvType = builder.makeIntType(32);
1552 break;
1553 case glslang::EbtUint:
1554 spvType = builder.makeUintType(32);
1555 break;
John Kessenich426394d2015-07-23 10:22:48 -06001556 case glslang::EbtAtomicUint:
1557 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1558 spvType = builder.makeUintType(32);
1559 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001560 case glslang::EbtSampler:
1561 {
1562 const glslang::TSampler& sampler = type.getSampler();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001563 // an image is present, make its type
1564 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1565 sampler.image ? 2 : 1, TranslateImageFormat(type));
John Kessenich55e7d112015-11-15 21:33:39 -07001566 if (! sampler.image) {
John Kesseniche0b6cad2015-12-24 10:30:13 -07001567 spvType = builder.makeSampledImageType(spvType);
John Kessenich55e7d112015-11-15 21:33:39 -07001568 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001569 }
John Kessenich140f3df2015-06-26 16:58:36 -06001570 break;
1571 case glslang::EbtStruct:
1572 case glslang::EbtBlock:
1573 {
1574 // If we've seen this struct type, return it
1575 const glslang::TTypeList* glslangStruct = type.getStruct();
1576 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001577
1578 // Try to share structs for different layouts, but not yet for other
1579 // kinds of qualification (primarily not yet including interpolant qualification).
1580 if (! HasNonLayoutQualifiers(qualifier))
1581 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1582 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001583 break;
1584
1585 // else, we haven't seen it...
1586
1587 // Create a vector of struct types for SPIR-V to consume
1588 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1589 if (type.getBasicType() == glslang::EbtBlock)
1590 memberRemapper[glslangStruct].resize(glslangStruct->size());
1591 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1592 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1593 if (glslangType.hiddenMember()) {
1594 ++memberDelta;
1595 if (type.getBasicType() == glslang::EbtBlock)
1596 memberRemapper[glslangStruct][i] = -1;
1597 } else {
1598 if (type.getBasicType() == glslang::EbtBlock)
1599 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001600 // modify just this child's view of the qualifier
1601 glslang::TQualifier subQualifier = glslangType.getQualifier();
1602 InheritQualifiers(subQualifier, qualifier);
1603 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001604 }
1605 }
1606
1607 // Make the SPIR-V type
1608 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001609 if (! HasNonLayoutQualifiers(qualifier))
1610 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001611
1612 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001613 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001614 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1615 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1616 int member = i;
1617 if (type.getBasicType() == glslang::EbtBlock)
1618 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001619
John Kesseniche0b6cad2015-12-24 10:30:13 -07001620 // modify just this child's view of the qualifier
1621 glslang::TQualifier subQualifier = glslangType.getQualifier();
1622 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001623
John Kessenich140f3df2015-06-26 16:58:36 -06001624 // using -1 above to indicate a hidden member
1625 if (member >= 0) {
1626 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001627 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001628 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001629 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1630 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001631 if (glslangType.getQualifier().hasLocation())
1632 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1633 if (glslangType.getQualifier().hasComponent())
1634 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1635 if (glslangType.getQualifier().hasXfbOffset())
1636 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001637 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001638 // figure out what to do with offset, which is accumulating
1639 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001640 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001641 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001642 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001643 offset = nextOffset;
1644 }
John Kessenich140f3df2015-06-26 16:58:36 -06001645
John Kessenichf85e8062015-12-19 13:57:10 -07001646 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001647 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001648
John Kessenich140f3df2015-06-26 16:58:36 -06001649 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001650 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1651 if (builtIn != spv::BadValue)
1652 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001653 }
1654 }
1655
1656 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001657 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001658 addDecoration(spvType, TranslateBlockDecoration(type));
1659 if (type.getQualifier().hasStream())
1660 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1661 if (glslangIntermediate->getXfbMode()) {
1662 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001663 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001664 if (type.getQualifier().hasXfbBuffer())
1665 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1666 }
1667 }
1668 break;
1669 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001670 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001671 break;
1672 }
1673
1674 if (type.isMatrix())
1675 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1676 else {
1677 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1678 if (type.getVectorSize() > 1)
1679 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1680 }
1681
1682 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001683 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1684
John Kessenichc9a80832015-09-12 12:17:44 -06001685 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001686 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001687 // We need to decorate array strides for types needing explicit layout, except blocks.
1688 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001689 // Use a dummy glslang type for querying internal strides of
1690 // arrays of arrays, but using just a one-dimensional array.
1691 glslang::TType simpleArrayType(type, 0); // deference type of the array
1692 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1693 simpleArrayType.getArraySizes().dereference();
1694
1695 // Will compute the higher-order strides here, rather than making a whole
1696 // pile of types and doing repetitive recursion on their contents.
1697 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1698 }
John Kessenichf8842e52016-01-04 19:22:56 -07001699
1700 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001701 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1702 int size = type.getArraySizes()->getDimSize(dim);
1703 assert(size > 0);
1704 spvType = builder.makeArrayType(spvType, size, stride);
1705 if (stride > 0)
1706 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
1707 stride *= size;
1708 }
1709 } else {
1710 // single-dimensional array, and don't yet have stride
1711
John Kessenichf8842e52016-01-04 19:22:56 -07001712 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001713 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1714 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001715 }
John Kessenich31ed4832015-09-09 17:51:38 -06001716
John Kessenichc9a80832015-09-12 12:17:44 -06001717 // Do the outer dimension, which might not be known for a runtime-sized array
1718 if (type.isRuntimeSizedArray()) {
1719 spvType = builder.makeRuntimeArray(spvType);
1720 } else {
1721 assert(type.getOuterArraySize() > 0);
John Kessenichc9e0a422015-12-29 21:27:24 -07001722 spvType = builder.makeArrayType(spvType, type.getOuterArraySize(), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001723 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001724 if (stride > 0)
1725 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001726 }
1727
1728 return spvType;
1729}
1730
John Kessenichf85e8062015-12-19 13:57:10 -07001731// Decide whether or not this type should be
1732// decorated with offsets and strides, and if so
1733// whether std140 or std430 rules should be applied.
1734glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001735{
John Kessenichf85e8062015-12-19 13:57:10 -07001736 // has to be a block
1737 if (type.getBasicType() != glslang::EbtBlock)
1738 return glslang::ElpNone;
1739
1740 // has to be a uniform or buffer block
1741 if (type.getQualifier().storage != glslang::EvqUniform &&
1742 type.getQualifier().storage != glslang::EvqBuffer)
1743 return glslang::ElpNone;
1744
1745 // return the layout to use
1746 switch (type.getQualifier().layoutPacking) {
1747 case glslang::ElpStd140:
1748 case glslang::ElpStd430:
1749 return type.getQualifier().layoutPacking;
1750 default:
1751 return glslang::ElpNone;
1752 }
John Kessenich31ed4832015-09-09 17:51:38 -06001753}
1754
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001755// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001756int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001757{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001758 int size;
John Kessenich49987892015-12-29 17:11:44 -07001759 int stride;
1760 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001761
1762 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001763}
1764
John Kessenich49987892015-12-29 17:11:44 -07001765// Given a matrix type, or array (of array) of matrixes type, returns the integer stride required for that matrix
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001766// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001767int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001768{
John Kessenich49987892015-12-29 17:11:44 -07001769 glslang::TType elementType;
1770 elementType.shallowCopy(matrixType);
1771 elementType.clearArraySizes();
1772
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001773 int size;
John Kessenich49987892015-12-29 17:11:44 -07001774 int stride;
1775 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
1776
1777 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001778}
1779
John Kessenich5e4b1242015-08-06 22:53:06 -06001780// Given a member type of a struct, realign the current offset for it, and compute
1781// the next (not yet aligned) offset for the next member, which will get aligned
1782// on the next call.
1783// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1784// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1785// -1 means a non-forced member offset (no decoration needed).
John Kessenichf85e8062015-12-19 13:57:10 -07001786void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07001787 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06001788{
1789 // this will get a positive value when deemed necessary
1790 nextOffset = -1;
1791
John Kessenich5e4b1242015-08-06 22:53:06 -06001792 // override anything in currentOffset with user-set offset
1793 if (memberType.getQualifier().hasOffset())
1794 currentOffset = memberType.getQualifier().layoutOffset;
1795
1796 // It could be that current linker usage in glslang updated all the layoutOffset,
1797 // in which case the following code does not matter. But, that's not quite right
1798 // once cross-compilation unit GLSL validation is done, as the original user
1799 // settings are needed in layoutOffset, and then the following will come into play.
1800
John Kessenichf85e8062015-12-19 13:57:10 -07001801 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001802 if (! memberType.getQualifier().hasOffset())
1803 currentOffset = -1;
1804
1805 return;
1806 }
1807
John Kessenichf85e8062015-12-19 13:57:10 -07001808 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06001809 if (currentOffset < 0)
1810 currentOffset = 0;
1811
1812 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1813 // but possibly not yet correctly aligned.
1814
1815 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07001816 int dummyStride;
1817 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06001818 glslang::RoundToPow2(currentOffset, memberAlignment);
1819 nextOffset = currentOffset + memberSize;
1820}
1821
John Kessenich140f3df2015-06-26 16:58:36 -06001822bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1823{
1824 return node->getName() == "main(";
1825}
1826
1827// Make all the functions, skeletally, without actually visiting their bodies.
1828void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1829{
1830 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1831 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1832 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1833 continue;
1834
1835 // We're on a user function. Set up the basic interface for the function now,
1836 // so that it's available to call.
1837 // Translating the body will happen later.
1838 //
1839 // Typically (except for a "const in" parameter), an address will be passed to the
1840 // function. What it is an address of varies:
1841 //
1842 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1843 // so that write needs to be to a copy, hence the address of a copy works.
1844 //
1845 // - "const in" parameters can just be the r-value, as no writes need occur.
1846 //
1847 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1848 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1849
1850 std::vector<spv::Id> paramTypes;
1851 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1852
1853 for (int p = 0; p < (int)parameters.size(); ++p) {
1854 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1855 spv::Id typeId = convertGlslangToSpvType(paramType);
1856 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1857 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1858 else
1859 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1860 paramTypes.push_back(typeId);
1861 }
1862
1863 spv::Block* functionBlock;
1864 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1865 paramTypes, &functionBlock);
1866
1867 // Track function to emit/call later
1868 functionMap[glslFunction->getName().c_str()] = function;
1869
1870 // Set the parameter id's
1871 for (int p = 0; p < (int)parameters.size(); ++p) {
1872 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1873 // give a name too
1874 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1875 }
1876 }
1877}
1878
1879// Process all the initializers, while skipping the functions and link objects
1880void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1881{
1882 builder.setBuildPoint(shaderEntry->getLastBlock());
1883 for (int i = 0; i < (int)initializers.size(); ++i) {
1884 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1885 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1886
1887 // We're on a top-level node that's not a function. Treat as an initializer, whose
1888 // code goes into the beginning of main.
1889 initializer->traverse(this);
1890 }
1891 }
1892}
1893
1894// Process all the functions, while skipping initializers.
1895void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1896{
1897 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1898 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1899 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1900 node->traverse(this);
1901 }
1902}
1903
1904void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1905{
1906 // SPIR-V functions should already be in the functionMap from the prepass
1907 // that called makeFunctions().
1908 spv::Function* function = functionMap[node->getName().c_str()];
1909 spv::Block* functionBlock = function->getEntryBlock();
1910 builder.setBuildPoint(functionBlock);
1911}
1912
Rex Xu04db3f52015-09-16 11:44:02 +08001913void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001914{
Rex Xufc618912015-09-09 16:42:49 +08001915 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08001916
1917 glslang::TSampler sampler = {};
1918 bool cubeCompare = false;
1919 if (node.isTexture()) {
1920 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
1921 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1922 }
1923
John Kessenich140f3df2015-06-26 16:58:36 -06001924 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1925 builder.clearAccessChain();
1926 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001927
1928 // Special case l-value operands
1929 bool lvalue = false;
1930 switch (node.getOp()) {
1931 case glslang::EOpImageAtomicAdd:
1932 case glslang::EOpImageAtomicMin:
1933 case glslang::EOpImageAtomicMax:
1934 case glslang::EOpImageAtomicAnd:
1935 case glslang::EOpImageAtomicOr:
1936 case glslang::EOpImageAtomicXor:
1937 case glslang::EOpImageAtomicExchange:
1938 case glslang::EOpImageAtomicCompSwap:
1939 if (i == 0)
1940 lvalue = true;
1941 break;
Rex Xu48edadf2015-12-31 16:11:41 +08001942 case glslang::EOpSparseTexture:
1943 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
1944 lvalue = true;
1945 break;
1946 case glslang::EOpSparseTextureClamp:
1947 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
1948 lvalue = true;
1949 break;
1950 case glslang::EOpSparseTextureLod:
1951 case glslang::EOpSparseTextureOffset:
1952 if (i == 3)
1953 lvalue = true;
1954 break;
1955 case glslang::EOpSparseTextureFetch:
1956 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
1957 lvalue = true;
1958 break;
1959 case glslang::EOpSparseTextureFetchOffset:
1960 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
1961 lvalue = true;
1962 break;
1963 case glslang::EOpSparseTextureLodOffset:
1964 case glslang::EOpSparseTextureGrad:
1965 case glslang::EOpSparseTextureOffsetClamp:
1966 if (i == 4)
1967 lvalue = true;
1968 break;
1969 case glslang::EOpSparseTextureGradOffset:
1970 case glslang::EOpSparseTextureGradClamp:
1971 if (i == 5)
1972 lvalue = true;
1973 break;
1974 case glslang::EOpSparseTextureGradOffsetClamp:
1975 if (i == 6)
1976 lvalue = true;
1977 break;
1978 case glslang::EOpSparseTextureGather:
1979 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
1980 lvalue = true;
1981 break;
1982 case glslang::EOpSparseTextureGatherOffset:
1983 case glslang::EOpSparseTextureGatherOffsets:
1984 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
1985 lvalue = true;
1986 break;
Rex Xufc618912015-09-09 16:42:49 +08001987 default:
1988 break;
1989 }
1990
Rex Xu6b86d492015-09-16 17:48:22 +08001991 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08001992 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08001993 else
Rex Xu30f92582015-09-14 10:38:56 +08001994 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001995 }
1996}
1997
John Kessenichfc51d282015-08-19 13:34:18 -06001998void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001999{
John Kessenichfc51d282015-08-19 13:34:18 -06002000 builder.clearAccessChain();
2001 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06002002 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06002003}
John Kessenich140f3df2015-06-26 16:58:36 -06002004
John Kessenichfc51d282015-08-19 13:34:18 -06002005spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2006{
Rex Xufc618912015-09-09 16:42:49 +08002007 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002008 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002009 }
2010
John Kessenichfc51d282015-08-19 13:34:18 -06002011 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002012 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2013 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2014 std::vector<spv::Id> arguments;
2015 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002016 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002017 else
2018 translateArguments(*node->getAsUnaryNode(), arguments);
2019 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2020
2021 spv::Builder::TextureParameters params = { };
2022 params.sampler = arguments[0];
2023
Rex Xu04db3f52015-09-16 11:44:02 +08002024 glslang::TCrackedTextureOp cracked;
2025 node->crackTexture(sampler, cracked);
2026
John Kessenichfc51d282015-08-19 13:34:18 -06002027 // Check for queries
2028 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002029 // a sampled image needs to have the image extracted first
2030 if (builder.isSampledImage(params.sampler))
2031 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002032 switch (node->getOp()) {
2033 case glslang::EOpImageQuerySize:
2034 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002035 if (arguments.size() > 1) {
2036 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002037 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002038 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002039 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002040 case glslang::EOpImageQuerySamples:
2041 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002042 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002043 case glslang::EOpTextureQueryLod:
2044 params.coords = arguments[1];
2045 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2046 case glslang::EOpTextureQueryLevels:
2047 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002048 case glslang::EOpSparseTexelsResident:
2049 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002050 default:
2051 assert(0);
2052 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002053 }
John Kessenich140f3df2015-06-26 16:58:36 -06002054 }
2055
Rex Xufc618912015-09-09 16:42:49 +08002056 // Check for image functions other than queries
2057 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002058 std::vector<spv::Id> operands;
2059 auto opIt = arguments.begin();
2060 operands.push_back(*(opIt++));
2061 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002062 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002063 if (sampler.ms) {
2064 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002065 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002066 }
John Kessenich56bab042015-09-16 10:54:31 -06002067 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2068 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002069 if (sampler.ms) {
2070 operands.push_back(*(opIt + 1));
2071 operands.push_back(spv::ImageOperandsSampleMask);
2072 operands.push_back(*opIt);
2073 } else
2074 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002075 builder.createNoResultOp(spv::OpImageWrite, operands);
2076 return spv::NoResult;
Rex Xu48edadf2015-12-31 16:11:41 +08002077 } else if (node->isSparseImage()) {
2078 spv::MissingFunctionality("sparse image functions");
2079 return spv::NoResult;
2080 }
2081 else {
Rex Xu6b86d492015-09-16 17:48:22 +08002082 // Process image atomic operations
2083
2084 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2085 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich56bab042015-09-16 10:54:31 -06002086 operands.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002087
Rex Xufc618912015-09-09 16:42:49 +08002088 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002089 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002090
2091 std::vector<spv::Id> operands;
2092 operands.push_back(pointer);
2093 for (; opIt != arguments.end(); ++opIt)
2094 operands.push_back(*opIt);
2095
Rex Xu04db3f52015-09-16 11:44:02 +08002096 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002097 }
2098 }
2099
2100 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002101 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002102 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2103
John Kessenichfc51d282015-08-19 13:34:18 -06002104 // check for bias argument
2105 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002106 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002107 int nonBiasArgCount = 2;
2108 if (cracked.offset)
2109 ++nonBiasArgCount;
2110 if (cracked.grad)
2111 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002112 if (cracked.lodClamp)
2113 ++nonBiasArgCount;
2114 if (sparse)
2115 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002116
2117 if ((int)arguments.size() > nonBiasArgCount)
2118 bias = true;
2119 }
2120
John Kessenichfc51d282015-08-19 13:34:18 -06002121 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002122
John Kessenichfc51d282015-08-19 13:34:18 -06002123 params.coords = arguments[1];
2124 int extraArgs = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07002125
2126 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002127 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002128 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002129 ++extraArgs;
2130 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002131 params.Dref = arguments[2];
2132 ++extraArgs;
2133 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002134 std::vector<spv::Id> indexes;
2135 int comp;
2136 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002137 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002138 else
2139 comp = builder.getNumComponents(params.coords) - 1;
2140 indexes.push_back(comp);
2141 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2142 }
2143 if (cracked.lod) {
2144 params.lod = arguments[2];
2145 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08002146 } else if (sampler.ms) {
2147 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002148 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002149 }
2150 if (cracked.grad) {
2151 params.gradX = arguments[2 + extraArgs];
2152 params.gradY = arguments[3 + extraArgs];
2153 extraArgs += 2;
2154 }
John Kessenich55e7d112015-11-15 21:33:39 -07002155 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002156 params.offset = arguments[2 + extraArgs];
2157 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002158 } else if (cracked.offsets) {
2159 params.offsets = arguments[2 + extraArgs];
2160 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002161 }
Rex Xu48edadf2015-12-31 16:11:41 +08002162 if (cracked.lodClamp) {
2163 params.lodClamp = arguments[2 + extraArgs];
2164 ++extraArgs;
2165 }
2166 if (sparse) {
2167 params.texelOut = arguments[2 + extraArgs];
2168 ++extraArgs;
2169 }
John Kessenichfc51d282015-08-19 13:34:18 -06002170 if (bias) {
2171 params.bias = arguments[2 + extraArgs];
2172 ++extraArgs;
2173 }
John Kessenich55e7d112015-11-15 21:33:39 -07002174 if (cracked.gather && ! sampler.shadow) {
2175 // default component is 0, if missing, otherwise an argument
2176 if (2 + extraArgs < (int)arguments.size()) {
2177 params.comp = arguments[2 + extraArgs];
2178 ++extraArgs;
2179 } else {
2180 params.comp = builder.makeIntConstant(0);
2181 }
2182 }
John Kessenichfc51d282015-08-19 13:34:18 -06002183
Rex Xu48edadf2015-12-31 16:11:41 +08002184 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002185}
2186
2187spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2188{
2189 // Grab the function's pointer from the previously created function
2190 spv::Function* function = functionMap[node->getName().c_str()];
2191 if (! function)
2192 return 0;
2193
2194 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2195 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2196
2197 // See comments in makeFunctions() for details about the semantics for parameter passing.
2198 //
2199 // These imply we need a four step process:
2200 // 1. Evaluate the arguments
2201 // 2. Allocate and make copies of in, out, and inout arguments
2202 // 3. Make the call
2203 // 4. Copy back the results
2204
2205 // 1. Evaluate the arguments
2206 std::vector<spv::Builder::AccessChain> lValues;
2207 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06002208 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002209 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2210 // build l-value
2211 builder.clearAccessChain();
2212 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06002213 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002214 // keep outputs as l-values, evaluate input-only as r-values
2215 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2216 // save l-value
2217 lValues.push_back(builder.getAccessChain());
2218 } else {
2219 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06002220 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002221 }
2222 }
2223
2224 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2225 // copy the original into that space.
2226 //
2227 // Also, build up the list of actual arguments to pass in for the call
2228 int lValueCount = 0;
2229 int rValueCount = 0;
2230 std::vector<spv::Id> spvArgs;
2231 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2232 spv::Id arg;
2233 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2234 // need space to hold the copy
2235 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2236 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2237 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2238 // need to copy the input into output space
2239 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06002240 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002241 builder.createStore(copy, arg);
2242 }
2243 ++lValueCount;
2244 } else {
2245 arg = rValues[rValueCount];
2246 ++rValueCount;
2247 }
2248 spvArgs.push_back(arg);
2249 }
2250
2251 // 3. Make the call.
2252 spv::Id result = builder.createFunctionCall(function, spvArgs);
2253
2254 // 4. Copy back out an "out" arguments.
2255 lValueCount = 0;
2256 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2257 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2258 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2259 spv::Id copy = builder.createLoad(spvArgs[a]);
2260 builder.setAccessChain(lValues[lValueCount]);
2261 builder.accessChainStore(copy);
2262 }
2263 ++lValueCount;
2264 }
2265 }
2266
2267 return result;
2268}
2269
2270// Translate AST operation to SPV operation, already having SPV-based operands/types.
2271spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2272 spv::Id typeId, spv::Id left, spv::Id right,
2273 glslang::TBasicType typeProxy, bool reduceComparison)
2274{
2275 bool isUnsigned = typeProxy == glslang::EbtUint;
2276 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2277
2278 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002279 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002280 bool comparison = false;
2281
2282 switch (op) {
2283 case glslang::EOpAdd:
2284 case glslang::EOpAddAssign:
2285 if (isFloat)
2286 binOp = spv::OpFAdd;
2287 else
2288 binOp = spv::OpIAdd;
2289 break;
2290 case glslang::EOpSub:
2291 case glslang::EOpSubAssign:
2292 if (isFloat)
2293 binOp = spv::OpFSub;
2294 else
2295 binOp = spv::OpISub;
2296 break;
2297 case glslang::EOpMul:
2298 case glslang::EOpMulAssign:
2299 if (isFloat)
2300 binOp = spv::OpFMul;
2301 else
2302 binOp = spv::OpIMul;
2303 break;
2304 case glslang::EOpVectorTimesScalar:
2305 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002306 if (isFloat) {
2307 if (builder.isVector(right))
2308 std::swap(left, right);
2309 assert(builder.isScalar(right));
2310 needMatchingVectors = false;
2311 binOp = spv::OpVectorTimesScalar;
2312 } else
2313 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002314 break;
2315 case glslang::EOpVectorTimesMatrix:
2316 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002317 binOp = spv::OpVectorTimesMatrix;
2318 break;
2319 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002320 binOp = spv::OpMatrixTimesVector;
2321 break;
2322 case glslang::EOpMatrixTimesScalar:
2323 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002324 binOp = spv::OpMatrixTimesScalar;
2325 break;
2326 case glslang::EOpMatrixTimesMatrix:
2327 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002328 binOp = spv::OpMatrixTimesMatrix;
2329 break;
2330 case glslang::EOpOuterProduct:
2331 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002332 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002333 break;
2334
2335 case glslang::EOpDiv:
2336 case glslang::EOpDivAssign:
2337 if (isFloat)
2338 binOp = spv::OpFDiv;
2339 else if (isUnsigned)
2340 binOp = spv::OpUDiv;
2341 else
2342 binOp = spv::OpSDiv;
2343 break;
2344 case glslang::EOpMod:
2345 case glslang::EOpModAssign:
2346 if (isFloat)
2347 binOp = spv::OpFMod;
2348 else if (isUnsigned)
2349 binOp = spv::OpUMod;
2350 else
2351 binOp = spv::OpSMod;
2352 break;
2353 case glslang::EOpRightShift:
2354 case glslang::EOpRightShiftAssign:
2355 if (isUnsigned)
2356 binOp = spv::OpShiftRightLogical;
2357 else
2358 binOp = spv::OpShiftRightArithmetic;
2359 break;
2360 case glslang::EOpLeftShift:
2361 case glslang::EOpLeftShiftAssign:
2362 binOp = spv::OpShiftLeftLogical;
2363 break;
2364 case glslang::EOpAnd:
2365 case glslang::EOpAndAssign:
2366 binOp = spv::OpBitwiseAnd;
2367 break;
2368 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002369 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002370 binOp = spv::OpLogicalAnd;
2371 break;
2372 case glslang::EOpInclusiveOr:
2373 case glslang::EOpInclusiveOrAssign:
2374 binOp = spv::OpBitwiseOr;
2375 break;
2376 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002377 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002378 binOp = spv::OpLogicalOr;
2379 break;
2380 case glslang::EOpExclusiveOr:
2381 case glslang::EOpExclusiveOrAssign:
2382 binOp = spv::OpBitwiseXor;
2383 break;
2384 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002385 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002386 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002387 break;
2388
2389 case glslang::EOpLessThan:
2390 case glslang::EOpGreaterThan:
2391 case glslang::EOpLessThanEqual:
2392 case glslang::EOpGreaterThanEqual:
2393 case glslang::EOpEqual:
2394 case glslang::EOpNotEqual:
2395 case glslang::EOpVectorEqual:
2396 case glslang::EOpVectorNotEqual:
2397 comparison = true;
2398 break;
2399 default:
2400 break;
2401 }
2402
John Kessenich7c1aa102015-10-15 13:29:11 -06002403 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002404 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002405 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002406 if (builder.isMatrix(left) || builder.isMatrix(right))
2407 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002408
2409 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002410 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002411 builder.promoteScalar(precision, left, right);
2412
2413 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2414 builder.setPrecision(id, precision);
2415
2416 return id;
2417 }
2418
2419 if (! comparison)
2420 return 0;
2421
John Kessenich7c1aa102015-10-15 13:29:11 -06002422 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002423
2424 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2425 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2426
John Kessenich22118352015-12-21 20:54:09 -07002427 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002428 }
2429
2430 switch (op) {
2431 case glslang::EOpLessThan:
2432 if (isFloat)
2433 binOp = spv::OpFOrdLessThan;
2434 else if (isUnsigned)
2435 binOp = spv::OpULessThan;
2436 else
2437 binOp = spv::OpSLessThan;
2438 break;
2439 case glslang::EOpGreaterThan:
2440 if (isFloat)
2441 binOp = spv::OpFOrdGreaterThan;
2442 else if (isUnsigned)
2443 binOp = spv::OpUGreaterThan;
2444 else
2445 binOp = spv::OpSGreaterThan;
2446 break;
2447 case glslang::EOpLessThanEqual:
2448 if (isFloat)
2449 binOp = spv::OpFOrdLessThanEqual;
2450 else if (isUnsigned)
2451 binOp = spv::OpULessThanEqual;
2452 else
2453 binOp = spv::OpSLessThanEqual;
2454 break;
2455 case glslang::EOpGreaterThanEqual:
2456 if (isFloat)
2457 binOp = spv::OpFOrdGreaterThanEqual;
2458 else if (isUnsigned)
2459 binOp = spv::OpUGreaterThanEqual;
2460 else
2461 binOp = spv::OpSGreaterThanEqual;
2462 break;
2463 case glslang::EOpEqual:
2464 case glslang::EOpVectorEqual:
2465 if (isFloat)
2466 binOp = spv::OpFOrdEqual;
2467 else
2468 binOp = spv::OpIEqual;
2469 break;
2470 case glslang::EOpNotEqual:
2471 case glslang::EOpVectorNotEqual:
2472 if (isFloat)
2473 binOp = spv::OpFOrdNotEqual;
2474 else
2475 binOp = spv::OpINotEqual;
2476 break;
2477 default:
2478 break;
2479 }
2480
2481 if (binOp != spv::OpNop) {
2482 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2483 builder.setPrecision(id, precision);
2484
2485 return id;
2486 }
2487
2488 return 0;
2489}
2490
John Kessenich04bb8a02015-12-12 12:28:14 -07002491//
2492// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2493// These can be any of:
2494//
2495// matrix * scalar
2496// scalar * matrix
2497// matrix * matrix linear algebraic
2498// matrix * vector
2499// vector * matrix
2500// matrix * matrix componentwise
2501// matrix op matrix op in {+, -, /}
2502// matrix op scalar op in {+, -, /}
2503// scalar op matrix op in {+, -, /}
2504//
2505spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2506{
2507 bool firstClass = true;
2508
2509 // First, handle first-class matrix operations (* and matrix/scalar)
2510 switch (op) {
2511 case spv::OpFDiv:
2512 if (builder.isMatrix(left) && builder.isScalar(right)) {
2513 // turn matrix / scalar into a multiply...
2514 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2515 op = spv::OpMatrixTimesScalar;
2516 } else
2517 firstClass = false;
2518 break;
2519 case spv::OpMatrixTimesScalar:
2520 if (builder.isMatrix(right))
2521 std::swap(left, right);
2522 assert(builder.isScalar(right));
2523 break;
2524 case spv::OpVectorTimesMatrix:
2525 assert(builder.isVector(left));
2526 assert(builder.isMatrix(right));
2527 break;
2528 case spv::OpMatrixTimesVector:
2529 assert(builder.isMatrix(left));
2530 assert(builder.isVector(right));
2531 break;
2532 case spv::OpMatrixTimesMatrix:
2533 assert(builder.isMatrix(left));
2534 assert(builder.isMatrix(right));
2535 break;
2536 default:
2537 firstClass = false;
2538 break;
2539 }
2540
2541 if (firstClass) {
2542 spv::Id id = builder.createBinOp(op, typeId, left, right);
2543 builder.setPrecision(id, precision);
2544
2545 return id;
2546 }
2547
2548 // Handle component-wise +, -, *, and / for all combinations of type.
2549 // The result type of all of them is the same type as the (a) matrix operand.
2550 // The algorithm is to:
2551 // - break the matrix(es) into vectors
2552 // - smear any scalar to a vector
2553 // - do vector operations
2554 // - make a matrix out the vector results
2555 switch (op) {
2556 case spv::OpFAdd:
2557 case spv::OpFSub:
2558 case spv::OpFDiv:
2559 case spv::OpFMul:
2560 {
2561 // one time set up...
2562 bool leftMat = builder.isMatrix(left);
2563 bool rightMat = builder.isMatrix(right);
2564 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2565 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2566 spv::Id scalarType = builder.getScalarTypeId(typeId);
2567 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2568 std::vector<spv::Id> results;
2569 spv::Id smearVec = spv::NoResult;
2570 if (builder.isScalar(left))
2571 smearVec = builder.smearScalar(precision, left, vecType);
2572 else if (builder.isScalar(right))
2573 smearVec = builder.smearScalar(precision, right, vecType);
2574
2575 // do each vector op
2576 for (unsigned int c = 0; c < numCols; ++c) {
2577 std::vector<unsigned int> indexes;
2578 indexes.push_back(c);
2579 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2580 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2581 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2582 builder.setPrecision(results.back(), precision);
2583 }
2584
2585 // put the pieces together
2586 spv::Id id = builder.createCompositeConstruct(typeId, results);
2587 builder.setPrecision(id, precision);
2588 return id;
2589 }
2590 default:
2591 assert(0);
2592 return spv::NoResult;
2593 }
2594}
2595
Rex Xu04db3f52015-09-16 11:44:02 +08002596spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06002597{
2598 spv::Op unaryOp = spv::OpNop;
2599 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002600 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002601 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002602
2603 switch (op) {
2604 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002605 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002606 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002607 if (builder.isMatrixType(typeId))
2608 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2609 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002610 unaryOp = spv::OpSNegate;
2611 break;
2612
2613 case glslang::EOpLogicalNot:
2614 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002615 unaryOp = spv::OpLogicalNot;
2616 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002617 case glslang::EOpBitwiseNot:
2618 unaryOp = spv::OpNot;
2619 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002620
John Kessenich140f3df2015-06-26 16:58:36 -06002621 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002622 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002623 break;
2624 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002625 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002626 break;
2627 case glslang::EOpTranspose:
2628 unaryOp = spv::OpTranspose;
2629 break;
2630
2631 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002632 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002633 break;
2634 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002635 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002636 break;
2637 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002638 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002639 break;
2640 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002641 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002642 break;
2643 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002644 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002645 break;
2646 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002647 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002648 break;
2649 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002650 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002651 break;
2652 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002653 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002654 break;
2655
2656 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002657 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002658 break;
2659 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002660 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002661 break;
2662 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002663 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002664 break;
2665 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002666 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002667 break;
2668 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002669 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002670 break;
2671 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002672 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002673 break;
2674
2675 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002676 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002677 break;
2678 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002679 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002680 break;
2681
2682 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002683 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002684 break;
2685 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002686 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002687 break;
2688 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002689 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002690 break;
2691 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002692 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002693 break;
2694 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002695 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002696 break;
2697 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002698 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002699 break;
2700
2701 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002702 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002703 break;
2704 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002705 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002706 break;
2707 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002708 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002709 break;
2710 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002711 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002712 break;
2713 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002714 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002715 break;
2716 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002717 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002718 break;
2719
2720 case glslang::EOpIsNan:
2721 unaryOp = spv::OpIsNan;
2722 break;
2723 case glslang::EOpIsInf:
2724 unaryOp = spv::OpIsInf;
2725 break;
2726
Rex Xucbc426e2015-12-15 16:03:10 +08002727 case glslang::EOpFloatBitsToInt:
2728 case glslang::EOpFloatBitsToUint:
2729 case glslang::EOpIntBitsToFloat:
2730 case glslang::EOpUintBitsToFloat:
2731 unaryOp = spv::OpBitcast;
2732 break;
2733
John Kessenich140f3df2015-06-26 16:58:36 -06002734 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002735 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002736 break;
2737 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002738 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002739 break;
2740 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002741 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002742 break;
2743 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002744 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002745 break;
2746 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002747 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002748 break;
2749 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002750 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002751 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002752 case glslang::EOpPackSnorm4x8:
2753 libCall = spv::GLSLstd450PackSnorm4x8;
2754 break;
2755 case glslang::EOpUnpackSnorm4x8:
2756 libCall = spv::GLSLstd450UnpackSnorm4x8;
2757 break;
2758 case glslang::EOpPackUnorm4x8:
2759 libCall = spv::GLSLstd450PackUnorm4x8;
2760 break;
2761 case glslang::EOpUnpackUnorm4x8:
2762 libCall = spv::GLSLstd450UnpackUnorm4x8;
2763 break;
2764 case glslang::EOpPackDouble2x32:
2765 libCall = spv::GLSLstd450PackDouble2x32;
2766 break;
2767 case glslang::EOpUnpackDouble2x32:
2768 libCall = spv::GLSLstd450UnpackDouble2x32;
2769 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002770
2771 case glslang::EOpDPdx:
2772 unaryOp = spv::OpDPdx;
2773 break;
2774 case glslang::EOpDPdy:
2775 unaryOp = spv::OpDPdy;
2776 break;
2777 case glslang::EOpFwidth:
2778 unaryOp = spv::OpFwidth;
2779 break;
2780 case glslang::EOpDPdxFine:
2781 unaryOp = spv::OpDPdxFine;
2782 break;
2783 case glslang::EOpDPdyFine:
2784 unaryOp = spv::OpDPdyFine;
2785 break;
2786 case glslang::EOpFwidthFine:
2787 unaryOp = spv::OpFwidthFine;
2788 break;
2789 case glslang::EOpDPdxCoarse:
2790 unaryOp = spv::OpDPdxCoarse;
2791 break;
2792 case glslang::EOpDPdyCoarse:
2793 unaryOp = spv::OpDPdyCoarse;
2794 break;
2795 case glslang::EOpFwidthCoarse:
2796 unaryOp = spv::OpFwidthCoarse;
2797 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002798 case glslang::EOpInterpolateAtCentroid:
2799 libCall = spv::GLSLstd450InterpolateAtCentroid;
2800 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002801 case glslang::EOpAny:
2802 unaryOp = spv::OpAny;
2803 break;
2804 case glslang::EOpAll:
2805 unaryOp = spv::OpAll;
2806 break;
2807
2808 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002809 if (isFloat)
2810 libCall = spv::GLSLstd450FAbs;
2811 else
2812 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002813 break;
2814 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002815 if (isFloat)
2816 libCall = spv::GLSLstd450FSign;
2817 else
2818 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002819 break;
2820
John Kessenichfc51d282015-08-19 13:34:18 -06002821 case glslang::EOpAtomicCounterIncrement:
2822 case glslang::EOpAtomicCounterDecrement:
2823 case glslang::EOpAtomicCounter:
2824 {
2825 // Handle all of the atomics in one place, in createAtomicOperation()
2826 std::vector<spv::Id> operands;
2827 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002828 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002829 }
2830
2831 case glslang::EOpImageLoad:
2832 unaryOp = spv::OpImageRead;
2833 break;
2834
2835 case glslang::EOpBitFieldReverse:
2836 unaryOp = spv::OpBitReverse;
2837 break;
2838 case glslang::EOpBitCount:
2839 unaryOp = spv::OpBitCount;
2840 break;
2841 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002842 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002843 break;
2844 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002845 if (isUnsigned)
2846 libCall = spv::GLSLstd450FindUMsb;
2847 else
2848 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002849 break;
2850
John Kessenich140f3df2015-06-26 16:58:36 -06002851 default:
2852 return 0;
2853 }
2854
2855 spv::Id id;
2856 if (libCall >= 0) {
2857 std::vector<spv::Id> args;
2858 args.push_back(operand);
2859 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2860 } else
2861 id = builder.createUnaryOp(unaryOp, typeId, operand);
2862
2863 builder.setPrecision(id, precision);
2864
2865 return id;
2866}
2867
John Kessenich7a53f762016-01-20 11:19:27 -07002868// Create a unary operation on a matrix
2869spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
2870{
2871 // Handle unary operations vector by vector.
2872 // The result type is the same type as the original type.
2873 // The algorithm is to:
2874 // - break the matrix into vectors
2875 // - apply the operation to each vector
2876 // - make a matrix out the vector results
2877
2878 // get the types sorted out
2879 int numCols = builder.getNumColumns(operand);
2880 int numRows = builder.getNumRows(operand);
2881 spv::Id scalarType = builder.getScalarTypeId(typeId);
2882 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2883 std::vector<spv::Id> results;
2884
2885 // do each vector op
2886 for (int c = 0; c < numCols; ++c) {
2887 std::vector<unsigned int> indexes;
2888 indexes.push_back(c);
2889 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
2890 results.push_back(builder.createUnaryOp(op, vecType, vec));
2891 builder.setPrecision(results.back(), precision);
2892 }
2893
2894 // put the pieces together
2895 spv::Id id = builder.createCompositeConstruct(typeId, results);
2896 builder.setPrecision(id, precision);
2897
2898 return id;
2899}
2900
John Kessenich140f3df2015-06-26 16:58:36 -06002901spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2902{
2903 spv::Op convOp = spv::OpNop;
2904 spv::Id zero = 0;
2905 spv::Id one = 0;
2906
2907 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2908
2909 switch (op) {
2910 case glslang::EOpConvIntToBool:
2911 case glslang::EOpConvUintToBool:
2912 zero = builder.makeUintConstant(0);
2913 zero = makeSmearedConstant(zero, vectorSize);
2914 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2915
2916 case glslang::EOpConvFloatToBool:
2917 zero = builder.makeFloatConstant(0.0F);
2918 zero = makeSmearedConstant(zero, vectorSize);
2919 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2920
2921 case glslang::EOpConvDoubleToBool:
2922 zero = builder.makeDoubleConstant(0.0);
2923 zero = makeSmearedConstant(zero, vectorSize);
2924 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2925
2926 case glslang::EOpConvBoolToFloat:
2927 convOp = spv::OpSelect;
2928 zero = builder.makeFloatConstant(0.0);
2929 one = builder.makeFloatConstant(1.0);
2930 break;
2931 case glslang::EOpConvBoolToDouble:
2932 convOp = spv::OpSelect;
2933 zero = builder.makeDoubleConstant(0.0);
2934 one = builder.makeDoubleConstant(1.0);
2935 break;
2936 case glslang::EOpConvBoolToInt:
2937 zero = builder.makeIntConstant(0);
2938 one = builder.makeIntConstant(1);
2939 convOp = spv::OpSelect;
2940 break;
2941 case glslang::EOpConvBoolToUint:
2942 zero = builder.makeUintConstant(0);
2943 one = builder.makeUintConstant(1);
2944 convOp = spv::OpSelect;
2945 break;
2946
2947 case glslang::EOpConvIntToFloat:
2948 case glslang::EOpConvIntToDouble:
2949 convOp = spv::OpConvertSToF;
2950 break;
2951
2952 case glslang::EOpConvUintToFloat:
2953 case glslang::EOpConvUintToDouble:
2954 convOp = spv::OpConvertUToF;
2955 break;
2956
2957 case glslang::EOpConvDoubleToFloat:
2958 case glslang::EOpConvFloatToDouble:
2959 convOp = spv::OpFConvert;
2960 break;
2961
2962 case glslang::EOpConvFloatToInt:
2963 case glslang::EOpConvDoubleToInt:
2964 convOp = spv::OpConvertFToS;
2965 break;
2966
2967 case glslang::EOpConvUintToInt:
2968 case glslang::EOpConvIntToUint:
2969 convOp = spv::OpBitcast;
2970 break;
2971
2972 case glslang::EOpConvFloatToUint:
2973 case glslang::EOpConvDoubleToUint:
2974 convOp = spv::OpConvertFToU;
2975 break;
2976 default:
2977 break;
2978 }
2979
2980 spv::Id result = 0;
2981 if (convOp == spv::OpNop)
2982 return result;
2983
2984 if (convOp == spv::OpSelect) {
2985 zero = makeSmearedConstant(zero, vectorSize);
2986 one = makeSmearedConstant(one, vectorSize);
2987 result = builder.createTriOp(convOp, destType, operand, one, zero);
2988 } else
2989 result = builder.createUnaryOp(convOp, destType, operand);
2990
2991 builder.setPrecision(result, precision);
2992
2993 return result;
2994}
2995
2996spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2997{
2998 if (vectorSize == 0)
2999 return constant;
3000
3001 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3002 std::vector<spv::Id> components;
3003 for (int c = 0; c < vectorSize; ++c)
3004 components.push_back(constant);
3005 return builder.makeCompositeConstant(vectorTypeId, components);
3006}
3007
John Kessenich426394d2015-07-23 10:22:48 -06003008// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08003009spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich426394d2015-07-23 10:22:48 -06003010{
3011 spv::Op opCode = spv::OpNop;
3012
3013 switch (op) {
3014 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003015 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003016 opCode = spv::OpAtomicIAdd;
3017 break;
3018 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003019 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003020 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003021 break;
3022 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003023 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003024 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003025 break;
3026 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003027 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003028 opCode = spv::OpAtomicAnd;
3029 break;
3030 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003031 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003032 opCode = spv::OpAtomicOr;
3033 break;
3034 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003035 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003036 opCode = spv::OpAtomicXor;
3037 break;
3038 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003039 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003040 opCode = spv::OpAtomicExchange;
3041 break;
3042 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003043 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003044 opCode = spv::OpAtomicCompareExchange;
3045 break;
3046 case glslang::EOpAtomicCounterIncrement:
3047 opCode = spv::OpAtomicIIncrement;
3048 break;
3049 case glslang::EOpAtomicCounterDecrement:
3050 opCode = spv::OpAtomicIDecrement;
3051 break;
3052 case glslang::EOpAtomicCounter:
3053 opCode = spv::OpAtomicLoad;
3054 break;
3055 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003056 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003057 break;
3058 }
3059
3060 // Sort out the operands
3061 // - mapping from glslang -> SPV
3062 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003063 // - compare-exchange swaps the value and comparator
3064 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003065 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3066 auto opIt = operands.begin(); // walk the glslang operands
3067 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003068 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3069 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3070 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003071 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3072 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003073 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003074 spvAtomicOperands.push_back(*(opIt + 1));
3075 spvAtomicOperands.push_back(*opIt);
3076 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003077 }
John Kessenich426394d2015-07-23 10:22:48 -06003078
John Kessenich3e60a6f2015-09-14 22:45:16 -06003079 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003080 for (; opIt != operands.end(); ++opIt)
3081 spvAtomicOperands.push_back(*opIt);
3082
3083 return builder.createOp(opCode, typeId, spvAtomicOperands);
3084}
3085
John Kessenich5e4b1242015-08-06 22:53:06 -06003086spv::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 -06003087{
John Kessenich5e4b1242015-08-06 22:53:06 -06003088 bool isUnsigned = typeProxy == glslang::EbtUint;
3089 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3090
John Kessenich140f3df2015-06-26 16:58:36 -06003091 spv::Op opCode = spv::OpNop;
3092 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003093 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003094 spv::Id typeId0 = 0;
3095 if (consumedOperands > 0)
3096 typeId0 = builder.getTypeId(operands[0]);
3097 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003098
3099 switch (op) {
3100 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003101 if (isFloat)
3102 libCall = spv::GLSLstd450FMin;
3103 else if (isUnsigned)
3104 libCall = spv::GLSLstd450UMin;
3105 else
3106 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003107 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003108 break;
3109 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003110 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003111 break;
3112 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003113 if (isFloat)
3114 libCall = spv::GLSLstd450FMax;
3115 else if (isUnsigned)
3116 libCall = spv::GLSLstd450UMax;
3117 else
3118 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003119 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003120 break;
3121 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003122 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003123 break;
3124 case glslang::EOpDot:
3125 opCode = spv::OpDot;
3126 break;
3127 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003128 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003129 break;
3130
3131 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003132 if (isFloat)
3133 libCall = spv::GLSLstd450FClamp;
3134 else if (isUnsigned)
3135 libCall = spv::GLSLstd450UClamp;
3136 else
3137 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003138 builder.promoteScalar(precision, operands.front(), operands[1]);
3139 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003140 break;
3141 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003142 if (isFloat)
3143 libCall = spv::GLSLstd450FMix;
3144 else
3145 libCall = spv::GLSLstd450IMix;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003146 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003147 break;
3148 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003149 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003150 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003151 break;
3152 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003153 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003154 builder.promoteScalar(precision, operands[0], operands[2]);
3155 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003156 break;
3157
3158 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003159 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003160 break;
3161 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003162 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003163 break;
3164 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003165 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003166 break;
3167 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003168 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003169 break;
3170 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003171 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003172 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003173 case glslang::EOpInterpolateAtSample:
3174 libCall = spv::GLSLstd450InterpolateAtSample;
3175 break;
3176 case glslang::EOpInterpolateAtOffset:
3177 libCall = spv::GLSLstd450InterpolateAtOffset;
3178 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003179 case glslang::EOpAddCarry:
3180 opCode = spv::OpIAddCarry;
3181 typeId = builder.makeStructResultType(typeId0, typeId0);
3182 consumedOperands = 2;
3183 break;
3184 case glslang::EOpSubBorrow:
3185 opCode = spv::OpISubBorrow;
3186 typeId = builder.makeStructResultType(typeId0, typeId0);
3187 consumedOperands = 2;
3188 break;
3189 case glslang::EOpUMulExtended:
3190 opCode = spv::OpUMulExtended;
3191 typeId = builder.makeStructResultType(typeId0, typeId0);
3192 consumedOperands = 2;
3193 break;
3194 case glslang::EOpIMulExtended:
3195 opCode = spv::OpSMulExtended;
3196 typeId = builder.makeStructResultType(typeId0, typeId0);
3197 consumedOperands = 2;
3198 break;
3199 case glslang::EOpBitfieldExtract:
3200 if (isUnsigned)
3201 opCode = spv::OpBitFieldUExtract;
3202 else
3203 opCode = spv::OpBitFieldSExtract;
3204 break;
3205 case glslang::EOpBitfieldInsert:
3206 opCode = spv::OpBitFieldInsert;
3207 break;
3208
3209 case glslang::EOpFma:
3210 libCall = spv::GLSLstd450Fma;
3211 break;
3212 case glslang::EOpFrexp:
3213 libCall = spv::GLSLstd450FrexpStruct;
3214 if (builder.getNumComponents(operands[0]) == 1)
3215 frexpIntType = builder.makeIntegerType(32, true);
3216 else
3217 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3218 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3219 consumedOperands = 1;
3220 break;
3221 case glslang::EOpLdexp:
3222 libCall = spv::GLSLstd450Ldexp;
3223 break;
3224
John Kessenich140f3df2015-06-26 16:58:36 -06003225 default:
3226 return 0;
3227 }
3228
3229 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003230 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003231 // Use an extended instruction from the standard library.
3232 // Construct the call arguments, without modifying the original operands vector.
3233 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3234 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
3235 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003236 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003237 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003238 case 0:
3239 // should all be handled by visitAggregate and createNoArgOperation
3240 assert(0);
3241 return 0;
3242 case 1:
3243 // should all be handled by createUnaryOperation
3244 assert(0);
3245 return 0;
3246 case 2:
3247 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3248 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003249 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003250 // anything 3 or over doesn't have l-value operands, so all should be consumed
3251 assert(consumedOperands == operands.size());
3252 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003253 break;
3254 }
3255 }
3256
John Kessenich55e7d112015-11-15 21:33:39 -07003257 // Decode the return types that were structures
3258 switch (op) {
3259 case glslang::EOpAddCarry:
3260 case glslang::EOpSubBorrow:
3261 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3262 id = builder.createCompositeExtract(id, typeId0, 0);
3263 break;
3264 case glslang::EOpUMulExtended:
3265 case glslang::EOpIMulExtended:
3266 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3267 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3268 break;
3269 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003270 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003271 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3272 id = builder.createCompositeExtract(id, typeId0, 0);
3273 break;
3274 default:
3275 break;
3276 }
3277
John Kessenich140f3df2015-06-26 16:58:36 -06003278 builder.setPrecision(id, precision);
3279
3280 return id;
3281}
3282
3283// Intrinsics with no arguments, no return value, and no precision.
3284spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3285{
3286 // TODO: get the barrier operands correct
3287
3288 switch (op) {
3289 case glslang::EOpEmitVertex:
3290 builder.createNoResultOp(spv::OpEmitVertex);
3291 return 0;
3292 case glslang::EOpEndPrimitive:
3293 builder.createNoResultOp(spv::OpEndPrimitive);
3294 return 0;
3295 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003296 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3297 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003298 return 0;
3299 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003300 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003301 return 0;
3302 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003303 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003304 return 0;
3305 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003306 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003307 return 0;
3308 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003309 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003310 return 0;
3311 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003312 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003313 return 0;
3314 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003315 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003316 return 0;
3317 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003318 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003319 return 0;
3320 }
3321}
3322
3323spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3324{
John Kessenich2f273362015-07-18 22:34:27 -06003325 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003326 spv::Id id;
3327 if (symbolValues.end() != iter) {
3328 id = iter->second;
3329 return id;
3330 }
3331
3332 // it was not found, create it
3333 id = createSpvVariable(symbol);
3334 symbolValues[symbol->getId()] = id;
3335
3336 if (! symbol->getType().isStruct()) {
3337 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003338 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003339 if (symbol->getQualifier().hasLocation())
3340 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3341 if (symbol->getQualifier().hasIndex())
3342 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3343 if (symbol->getQualifier().hasComponent())
3344 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3345 if (glslangIntermediate->getXfbMode()) {
3346 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003347 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003348 if (symbol->getQualifier().hasXfbBuffer())
3349 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3350 if (symbol->getQualifier().hasXfbOffset())
3351 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3352 }
3353 }
3354
John Kesseniche0b6cad2015-12-24 10:30:13 -07003355 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003356 if (symbol->getQualifier().hasStream())
3357 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
3358 if (symbol->getQualifier().hasSet())
3359 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3360 if (symbol->getQualifier().hasBinding())
3361 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3362 if (glslangIntermediate->getXfbMode()) {
3363 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003364 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003365 if (symbol->getQualifier().hasXfbBuffer())
3366 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3367 }
3368
3369 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003370 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003371 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06003372 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003373
John Kessenich140f3df2015-06-26 16:58:36 -06003374 return id;
3375}
3376
John Kessenich55e7d112015-11-15 21:33:39 -07003377// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003378void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3379{
3380 if (dec != spv::BadValue)
3381 builder.addDecoration(id, dec);
3382}
3383
John Kessenich55e7d112015-11-15 21:33:39 -07003384// If 'dec' is valid, add a one-operand decoration to an object
3385void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3386{
3387 if (dec != spv::BadValue)
3388 builder.addDecoration(id, dec, value);
3389}
3390
3391// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003392void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3393{
3394 if (dec != spv::BadValue)
3395 builder.addMemberDecoration(id, (unsigned)member, dec);
3396}
3397
John Kessenich55e7d112015-11-15 21:33:39 -07003398// Make a full tree of instructions to build a SPIR-V specialization constant,
3399// or regularly constant if possible.
3400//
3401// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3402//
3403// Recursively walk the nodes. The nodes form a tree whose leaves are
3404// regular constants, which themselves are trees that createSpvConstant()
3405// recursively walks. So, this function walks the "top" of the tree:
3406// - emit specialization constant-building instructions for specConstant
3407// - when running into a non-spec-constant, switch to createSpvConstant()
3408spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3409{
3410 assert(node.getQualifier().storage == glslang::EvqConst);
3411
3412 // hand off to the non-spec-constant path
3413 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3414 int nextConst = 0;
3415 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3416}
3417
John Kessenich140f3df2015-06-26 16:58:36 -06003418// Use 'consts' as the flattened glslang source of scalar constants to recursively
3419// build the aggregate SPIR-V constant.
3420//
3421// If there are not enough elements present in 'consts', 0 will be substituted;
3422// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3423//
John Kessenich55e7d112015-11-15 21:33:39 -07003424spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003425{
3426 // vector of constants for SPIR-V
3427 std::vector<spv::Id> spvConsts;
3428
3429 // Type is used for struct and array constants
3430 spv::Id typeId = convertGlslangToSpvType(glslangType);
3431
3432 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003433 glslang::TType elementType(glslangType, 0);
3434 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003435 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003436 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003437 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003438 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003439 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003440 } else if (glslangType.getStruct()) {
3441 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3442 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003443 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003444 } else if (glslangType.isVector()) {
3445 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3446 bool zero = nextConst >= consts.size();
3447 switch (glslangType.getBasicType()) {
3448 case glslang::EbtInt:
3449 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3450 break;
3451 case glslang::EbtUint:
3452 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3453 break;
3454 case glslang::EbtFloat:
3455 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3456 break;
3457 case glslang::EbtDouble:
3458 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3459 break;
3460 case glslang::EbtBool:
3461 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3462 break;
3463 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003464 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003465 break;
3466 }
3467 ++nextConst;
3468 }
3469 } else {
3470 // we have a non-aggregate (scalar) constant
3471 bool zero = nextConst >= consts.size();
3472 spv::Id scalar = 0;
3473 switch (glslangType.getBasicType()) {
3474 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003475 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003476 break;
3477 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003478 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003479 break;
3480 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003481 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003482 break;
3483 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003484 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003485 break;
3486 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003487 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003488 break;
3489 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003490 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003491 break;
3492 }
3493 ++nextConst;
3494 return scalar;
3495 }
3496
3497 return builder.makeCompositeConstant(typeId, spvConsts);
3498}
3499
John Kessenich7c1aa102015-10-15 13:29:11 -06003500// Return true if the node is a constant or symbol whose reading has no
3501// non-trivial observable cost or effect.
3502bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3503{
3504 // don't know what this is
3505 if (node == nullptr)
3506 return false;
3507
3508 // a constant is safe
3509 if (node->getAsConstantUnion() != nullptr)
3510 return true;
3511
3512 // not a symbol means non-trivial
3513 if (node->getAsSymbolNode() == nullptr)
3514 return false;
3515
3516 // a symbol, depends on what's being read
3517 switch (node->getType().getQualifier().storage) {
3518 case glslang::EvqTemporary:
3519 case glslang::EvqGlobal:
3520 case glslang::EvqIn:
3521 case glslang::EvqInOut:
3522 case glslang::EvqConst:
3523 case glslang::EvqConstReadOnly:
3524 case glslang::EvqUniform:
3525 return true;
3526 default:
3527 return false;
3528 }
3529}
3530
3531// A node is trivial if it is a single operation with no side effects.
3532// Error on the side of saying non-trivial.
3533// Return true if trivial.
3534bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3535{
3536 if (node == nullptr)
3537 return false;
3538
3539 // symbols and constants are trivial
3540 if (isTrivialLeaf(node))
3541 return true;
3542
3543 // otherwise, it needs to be a simple operation or one or two leaf nodes
3544
3545 // not a simple operation
3546 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3547 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3548 if (binaryNode == nullptr && unaryNode == nullptr)
3549 return false;
3550
3551 // not on leaf nodes
3552 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3553 return false;
3554
3555 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3556 return false;
3557 }
3558
3559 switch (node->getAsOperator()->getOp()) {
3560 case glslang::EOpLogicalNot:
3561 case glslang::EOpConvIntToBool:
3562 case glslang::EOpConvUintToBool:
3563 case glslang::EOpConvFloatToBool:
3564 case glslang::EOpConvDoubleToBool:
3565 case glslang::EOpEqual:
3566 case glslang::EOpNotEqual:
3567 case glslang::EOpLessThan:
3568 case glslang::EOpGreaterThan:
3569 case glslang::EOpLessThanEqual:
3570 case glslang::EOpGreaterThanEqual:
3571 case glslang::EOpIndexDirect:
3572 case glslang::EOpIndexDirectStruct:
3573 case glslang::EOpLogicalXor:
3574 case glslang::EOpAny:
3575 case glslang::EOpAll:
3576 return true;
3577 default:
3578 return false;
3579 }
3580}
3581
3582// Emit short-circuiting code, where 'right' is never evaluated unless
3583// the left side is true (for &&) or false (for ||).
3584spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3585{
3586 spv::Id boolTypeId = builder.makeBoolType();
3587
3588 // emit left operand
3589 builder.clearAccessChain();
3590 left.traverse(this);
3591 spv::Id leftId = builder.accessChainLoad(boolTypeId);
3592
3593 // Operands to accumulate OpPhi operands
3594 std::vector<spv::Id> phiOperands;
3595 // accumulate left operand's phi information
3596 phiOperands.push_back(leftId);
3597 phiOperands.push_back(builder.getBuildPoint()->getId());
3598
3599 // Make the two kinds of operation symmetric with a "!"
3600 // || => emit "if (! left) result = right"
3601 // && => emit "if ( left) result = right"
3602 //
3603 // TODO: this runtime "not" for || could be avoided by adding functionality
3604 // to 'builder' to have an "else" without an "then"
3605 if (op == glslang::EOpLogicalOr)
3606 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3607
3608 // make an "if" based on the left value
3609 spv::Builder::If ifBuilder(leftId, builder);
3610
3611 // emit right operand as the "then" part of the "if"
3612 builder.clearAccessChain();
3613 right.traverse(this);
3614 spv::Id rightId = builder.accessChainLoad(boolTypeId);
3615
3616 // accumulate left operand's phi information
3617 phiOperands.push_back(rightId);
3618 phiOperands.push_back(builder.getBuildPoint()->getId());
3619
3620 // finish the "if"
3621 ifBuilder.makeEndIf();
3622
3623 // phi together the two results
3624 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3625}
3626
John Kessenich140f3df2015-06-26 16:58:36 -06003627}; // end anonymous namespace
3628
3629namespace glslang {
3630
John Kessenich68d78fd2015-07-12 19:28:10 -06003631void GetSpirvVersion(std::string& version)
3632{
John Kessenich9e55f632015-07-15 10:03:39 -06003633 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003634 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003635 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003636 version = buf;
3637}
3638
John Kessenich140f3df2015-06-26 16:58:36 -06003639// Write SPIR-V out to a binary file
3640void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3641{
3642 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003643 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003644 for (int i = 0; i < (int)spirv.size(); ++i) {
3645 unsigned int word = spirv[i];
3646 out.write((const char*)&word, 4);
3647 }
3648 out.close();
3649}
3650
3651//
3652// Set up the glslang traversal
3653//
3654void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3655{
3656 TIntermNode* root = intermediate.getTreeRoot();
3657
3658 if (root == 0)
3659 return;
3660
3661 glslang::GetThreadPoolAllocator().push();
3662
3663 TGlslangToSpvTraverser it(&intermediate);
3664
3665 root->traverse(&it);
3666
3667 it.dumpSpv(spirv);
3668
3669 glslang::GetThreadPoolAllocator().pop();
3670}
3671
3672}; // end namespace glslang