blob: becb3b43b39868a9c08294b338c1356acfa7592a [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich6c292d32016-02-15 20:58:50 -07002//Copyright (C) 2014-2015 LunarG, Inc.
3//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35
36//
37// Author: John Kessenich, LunarG
38//
39// Visit the nodes in the glslang intermediate tree representation to
40// translate them to SPIR-V.
41//
42
John Kessenich5e4b1242015-08-06 22:53:06 -060043#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060044#include "GlslangToSpv.h"
45#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060046namespace spv {
47 #include "GLSL.std.450.h"
48}
John Kessenich140f3df2015-06-26 16:58:36 -060049
50// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020051#include "../glslang/MachineIndependent/localintermediate.h"
52#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060054
55#include <string>
56#include <map>
57#include <list>
58#include <vector>
59#include <stack>
60#include <fstream>
61
62namespace {
63
John Kessenich55e7d112015-11-15 21:33:39 -070064// For low-order part of the generator's magic number. Bump up
65// when there is a change in the style (e.g., if SSA form changes,
66// or a different instruction sequence to do something gets used).
67const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060068
69//
70// The main holder of information for translating glslang to SPIR-V.
71//
72// Derives from the AST walking base class.
73//
74class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
75public:
76 TGlslangToSpvTraverser(const glslang::TIntermediate*);
77 virtual ~TGlslangToSpvTraverser();
78
79 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
80 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
81 void visitConstantUnion(glslang::TIntermConstantUnion*);
82 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
83 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
84 void visitSymbol(glslang::TIntermSymbol* symbol);
85 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
86 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
87 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
88
John Kessenich7ba63412015-12-20 17:37:07 -070089 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -060090
91protected:
John Kessenich5e801132016-02-15 11:09:46 -070092 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
John Kessenich92187592016-02-01 13:45:25 -070093 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable);
John Kessenich5d0fa972016-02-15 11:57:00 -070094 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -060095 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
96 spv::Id getSampledType(const glslang::TSampler&);
97 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -070098 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6c292d32016-02-15 20:58:50 -070099 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700100 spv::Id accessChainLoad(const glslang::TType& type);
John Kessenichf85e8062015-12-19 13:57:10 -0700101 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700102 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
103 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
104 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 -0600105
106 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
107 void makeFunctions(const glslang::TIntermSequence&);
108 void makeGlobalInitializers(const glslang::TIntermSequence&);
109 void visitFunctions(const glslang::TIntermSequence&);
110 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800111 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600112 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
113 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600114 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
115
116 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 -0700117 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800118 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 -0700119 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600120 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
121 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800122 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 -0600123 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 -0600124 spv::Id createNoArgOperation(glslang::TOperator op);
125 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
126 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700127 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600128 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700129 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
John Kessenich55e7d112015-11-15 21:33:39 -0700130 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
131 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600132 bool isTrivialLeaf(const glslang::TIntermTyped* node);
133 bool isTrivial(const glslang::TIntermTyped* node);
134 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600135
136 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700137 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600138 int sequenceDepth;
139
140 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
141 spv::Builder builder;
142 bool inMain;
143 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700144 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 -0700145 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600146 const glslang::TIntermediate* glslangIntermediate;
147 spv::Id stdBuiltins;
148
John Kessenich2f273362015-07-18 22:34:27 -0600149 std::unordered_map<int, spv::Id> symbolValues;
150 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
151 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700152 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600153 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 -0600154 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600155};
156
157//
158// Helper functions for translating glslang representations to SPIR-V enumerants.
159//
160
161// Translate glslang profile to SPIR-V source language.
162spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
163{
164 switch (profile) {
165 case ENoProfile:
166 case ECoreProfile:
167 case ECompatibilityProfile:
168 return spv::SourceLanguageGLSL;
169 case EEsProfile:
170 return spv::SourceLanguageESSL;
171 default:
172 return spv::SourceLanguageUnknown;
173 }
174}
175
176// Translate glslang language (stage) to SPIR-V execution model.
177spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
178{
179 switch (stage) {
180 case EShLangVertex: return spv::ExecutionModelVertex;
181 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
182 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
183 case EShLangGeometry: return spv::ExecutionModelGeometry;
184 case EShLangFragment: return spv::ExecutionModelFragment;
185 case EShLangCompute: return spv::ExecutionModelGLCompute;
186 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700187 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600188 return spv::ExecutionModelFragment;
189 }
190}
191
192// Translate glslang type to SPIR-V storage class.
193spv::StorageClass TranslateStorageClass(const glslang::TType& type)
194{
195 if (type.getQualifier().isPipeInput())
196 return spv::StorageClassInput;
197 else if (type.getQualifier().isPipeOutput())
198 return spv::StorageClassOutput;
199 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700200 if (type.getQualifier().layoutPushConstant)
201 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600202 if (type.getBasicType() == glslang::EbtBlock)
203 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800204 else if (type.getBasicType() == glslang::EbtAtomicUint)
205 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600206 else
207 return spv::StorageClassUniformConstant;
208 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
209 } else {
210 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700211 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
212 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600213 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
214 case glslang::EvqTemporary: return spv::StorageClassFunction;
215 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700216 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600217 return spv::StorageClassFunction;
218 }
219 }
220}
221
222// Translate glslang sampler type to SPIR-V dimensionality.
223spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
224{
225 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700226 case glslang::Esd1D: return spv::Dim1D;
227 case glslang::Esd2D: return spv::Dim2D;
228 case glslang::Esd3D: return spv::Dim3D;
229 case glslang::EsdCube: return spv::DimCube;
230 case glslang::EsdRect: return spv::DimRect;
231 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700232 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600233 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700234 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600235 return spv::Dim2D;
236 }
237}
238
239// Translate glslang type to SPIR-V precision decorations.
240spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
241{
242 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700243 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600244 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600245 default:
246 return spv::NoPrecision;
247 }
248}
249
250// Translate glslang type to SPIR-V block decorations.
251spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
252{
253 if (type.getBasicType() == glslang::EbtBlock) {
254 switch (type.getQualifier().storage) {
255 case glslang::EvqUniform: return spv::DecorationBlock;
256 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
257 case glslang::EvqVaryingIn: return spv::DecorationBlock;
258 case glslang::EvqVaryingOut: return spv::DecorationBlock;
259 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700260 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600261 break;
262 }
263 }
264
265 return (spv::Decoration)spv::BadValue;
266}
267
268// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700269spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600270{
271 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700272 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600273 case glslang::ElmRowMajor:
274 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700275 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600276 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700277 default:
278 // opaque layouts don't need a majorness
279 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600280 }
281 } else {
282 switch (type.getBasicType()) {
283 default:
284 return (spv::Decoration)spv::BadValue;
285 break;
286 case glslang::EbtBlock:
287 switch (type.getQualifier().storage) {
288 case glslang::EvqUniform:
289 case glslang::EvqBuffer:
290 switch (type.getQualifier().layoutPacking) {
291 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600292 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
293 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600294 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600295 }
296 case glslang::EvqVaryingIn:
297 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700298 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600299 return (spv::Decoration)spv::BadValue;
300 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700301 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600302 return (spv::Decoration)spv::BadValue;
303 }
304 }
305 }
306}
307
308// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700309// Returns spv::Decoration(spv::BadValue) when no decoration
310// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700311spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600312{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700313 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700314 // Smooth decoration doesn't exist in SPIR-V 1.0
315 return (spv::Decoration)spv::BadValue;
316 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700317 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700318 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700319 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600320 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700321 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600322 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700323 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600324 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700325 else if (qualifier.sample) {
326 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600327 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700328 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600329 return (spv::Decoration)spv::BadValue;
330}
331
John Kessenich92187592016-02-01 13:45:25 -0700332// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700333spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600334{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700335 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600336 return spv::DecorationInvariant;
337 else
338 return (spv::Decoration)spv::BadValue;
339}
340
341// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700342spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600343{
344 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700345 case glslang::EbvPointSize:
346 switch (glslangIntermediate->getStage()) {
347 case EShLangGeometry:
348 builder.addCapability(spv::CapabilityGeometryPointSize);
349 break;
350 case EShLangTessControl:
351 case EShLangTessEvaluation:
352 builder.addCapability(spv::CapabilityTessellationPointSize);
353 break;
354 }
355 return spv::BuiltInPointSize;
356
357 case glslang::EbvClipDistance:
358 builder.addCapability(spv::CapabilityClipDistance);
359 return spv::BuiltInClipDistance;
360
361 case glslang::EbvCullDistance:
362 builder.addCapability(spv::CapabilityCullDistance);
363 return spv::BuiltInCullDistance;
364
365 case glslang::EbvViewportIndex:
366 // TODO: builder.addCapability(spv::CapabilityMultiViewport);
367 return spv::BuiltInViewportIndex;
368
John Kessenich5e801132016-02-15 11:09:46 -0700369 case glslang::EbvSampleId:
370 builder.addCapability(spv::CapabilitySampleRateShading);
371 return spv::BuiltInSampleId;
372
373 case glslang::EbvSamplePosition:
374 builder.addCapability(spv::CapabilitySampleRateShading);
375 return spv::BuiltInSamplePosition;
376
377 case glslang::EbvSampleMask:
378 builder.addCapability(spv::CapabilitySampleRateShading);
379 return spv::BuiltInSampleMask;
380
John Kessenich140f3df2015-06-26 16:58:36 -0600381 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600382 case glslang::EbvVertexId: return spv::BuiltInVertexId;
383 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700384 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
385 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600386 case glslang::EbvBaseVertex:
387 case glslang::EbvBaseInstance:
388 case glslang::EbvDrawId:
389 // TODO: Add SPIR-V builtin ID.
390 spv::MissingFunctionality("Draw parameters");
391 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600392 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
393 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
394 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600395 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
396 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
397 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
398 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
399 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
400 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
401 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600402 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
403 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
404 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
405 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
406 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
407 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
408 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
409 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
410 default: return (spv::BuiltIn)spv::BadValue;
411 }
412}
413
Rex Xufc618912015-09-09 16:42:49 +0800414// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700415spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800416{
417 assert(type.getBasicType() == glslang::EbtSampler);
418
John Kessenich5d0fa972016-02-15 11:57:00 -0700419 // Check for capabilities
420 switch (type.getQualifier().layoutFormat) {
421 case glslang::ElfRg32f:
422 case glslang::ElfRg16f:
423 case glslang::ElfR11fG11fB10f:
424 case glslang::ElfR16f:
425 case glslang::ElfRgba16:
426 case glslang::ElfRgb10A2:
427 case glslang::ElfRg16:
428 case glslang::ElfRg8:
429 case glslang::ElfR16:
430 case glslang::ElfR8:
431 case glslang::ElfRgba16Snorm:
432 case glslang::ElfRg16Snorm:
433 case glslang::ElfRg8Snorm:
434 case glslang::ElfR16Snorm:
435 case glslang::ElfR8Snorm:
436
437 case glslang::ElfRg32i:
438 case glslang::ElfRg16i:
439 case glslang::ElfRg8i:
440 case glslang::ElfR16i:
441 case glslang::ElfR8i:
442
443 case glslang::ElfRgb10a2ui:
444 case glslang::ElfRg32ui:
445 case glslang::ElfRg16ui:
446 case glslang::ElfRg8ui:
447 case glslang::ElfR16ui:
448 case glslang::ElfR8ui:
449 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
450 break;
451
452 default:
453 break;
454 }
455
456 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800457 switch (type.getQualifier().layoutFormat) {
458 case glslang::ElfNone: return spv::ImageFormatUnknown;
459 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
460 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
461 case glslang::ElfR32f: return spv::ImageFormatR32f;
462 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
463 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
464 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
465 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
466 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
467 case glslang::ElfR16f: return spv::ImageFormatR16f;
468 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
469 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
470 case glslang::ElfRg16: return spv::ImageFormatRg16;
471 case glslang::ElfRg8: return spv::ImageFormatRg8;
472 case glslang::ElfR16: return spv::ImageFormatR16;
473 case glslang::ElfR8: return spv::ImageFormatR8;
474 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
475 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
476 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
477 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
478 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
479 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
480 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
481 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
482 case glslang::ElfR32i: return spv::ImageFormatR32i;
483 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
484 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
485 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
486 case glslang::ElfR16i: return spv::ImageFormatR16i;
487 case glslang::ElfR8i: return spv::ImageFormatR8i;
488 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
489 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
490 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
491 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
492 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
493 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
494 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
495 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
496 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
497 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
498 default: return (spv::ImageFormat)spv::BadValue;
499 }
500}
501
John Kessenich6c292d32016-02-15 20:58:50 -0700502// Return whether or not the given type is something that should be tied to a
503// descriptor set.
504bool IsDescriptorResource(const glslang::TType& type)
505{
506 // uniform and buffer blocks are included
507 if (type.getBasicType() == glslang::EbtBlock)
508 return type.getQualifier().isUniformOrBuffer();
509
510 // non block...
511 // basically samplerXXX/subpass/sampler/texture are all included
512 // if they are the global-scope-class, not the function parameter
513 // (or local, if they ever exist) class.
514 if (type.getBasicType() == glslang::EbtSampler)
515 return type.getQualifier().isUniformOrBuffer();
516
517 // None of the above.
518 return false;
519}
520
John Kesseniche0b6cad2015-12-24 10:30:13 -0700521void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
522{
523 if (child.layoutMatrix == glslang::ElmNone)
524 child.layoutMatrix = parent.layoutMatrix;
525
526 if (parent.invariant)
527 child.invariant = true;
528 if (parent.nopersp)
529 child.nopersp = true;
530 if (parent.flat)
531 child.flat = true;
532 if (parent.centroid)
533 child.centroid = true;
534 if (parent.patch)
535 child.patch = true;
536 if (parent.sample)
537 child.sample = true;
John Kessenich7b9fa252016-01-21 18:56:57 -0700538
539 child.layoutLocation = parent.layoutLocation;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700540}
541
542bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
543{
John Kessenich7b9fa252016-01-21 18:56:57 -0700544 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700545 // - struct members can inherit from a struct declaration
546 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
547 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700548 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700549}
550
John Kessenich140f3df2015-06-26 16:58:36 -0600551//
552// Implement the TGlslangToSpvTraverser class.
553//
554
555TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
556 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700557 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600558 inMain(false), mainTerminated(false), linkageOnly(false),
559 glslangIntermediate(glslangIntermediate)
560{
561 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
562
563 builder.clearAccessChain();
564 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
565 stdBuiltins = builder.import("GLSL.std.450");
566 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
567 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700568 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600569
570 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600571 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
572 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600573 builder.addSourceExtension(it->c_str());
574
575 // Add the top-level modes for this shader.
576
John Kessenich92187592016-02-01 13:45:25 -0700577 if (glslangIntermediate->getXfbMode()) {
578 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600579 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700580 }
John Kessenich140f3df2015-06-26 16:58:36 -0600581
582 unsigned int mode;
583 switch (glslangIntermediate->getStage()) {
584 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600585 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600586 break;
587
588 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600589 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600590 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
591 break;
592
593 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600594 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600595 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700596 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
597 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
598 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600599 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600600 }
601 if (mode != spv::BadValue)
602 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
603
John Kesseniche6903322015-10-13 16:29:02 -0600604 switch (glslangIntermediate->getVertexSpacing()) {
605 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
606 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
607 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
608 default: mode = spv::BadValue; break;
609 }
610 if (mode != spv::BadValue)
611 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
612
613 switch (glslangIntermediate->getVertexOrder()) {
614 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
615 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
616 default: mode = spv::BadValue; break;
617 }
618 if (mode != spv::BadValue)
619 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
620
621 if (glslangIntermediate->getPointMode())
622 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600623 break;
624
625 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600626 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600627 switch (glslangIntermediate->getInputPrimitive()) {
628 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
629 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
630 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700631 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600632 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
633 default: mode = spv::BadValue; break;
634 }
635 if (mode != spv::BadValue)
636 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600637
John Kessenich140f3df2015-06-26 16:58:36 -0600638 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
639
640 switch (glslangIntermediate->getOutputPrimitive()) {
641 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
642 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
643 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
644 default: mode = spv::BadValue; break;
645 }
646 if (mode != spv::BadValue)
647 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
648 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
649 break;
650
651 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600652 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600653 if (glslangIntermediate->getPixelCenterInteger())
654 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600655
John Kessenich140f3df2015-06-26 16:58:36 -0600656 if (glslangIntermediate->getOriginUpperLeft())
657 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600658 else
659 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600660
661 if (glslangIntermediate->getEarlyFragmentTests())
662 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
663
664 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600665 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
666 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
667 default: mode = spv::BadValue; break;
668 }
669 if (mode != spv::BadValue)
670 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
671
672 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
673 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600674 break;
675
676 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600677 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600678 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
679 glslangIntermediate->getLocalSize(1),
680 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600681 break;
682
683 default:
684 break;
685 }
686
687}
688
John Kessenich7ba63412015-12-20 17:37:07 -0700689// Finish everything and dump
690void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
691{
692 // finish off the entry-point SPV instruction by adding the Input/Output <id>
693 for (auto it : iOSet)
694 entryPoint->addIdOperand(it);
695
696 builder.dump(out);
697}
698
John Kessenich140f3df2015-06-26 16:58:36 -0600699TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
700{
701 if (! mainTerminated) {
702 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
703 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600704 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600705 }
706}
707
708//
709// Implement the traversal functions.
710//
711// Return true from interior nodes to have the external traversal
712// continue on to children. Return false if children were
713// already processed.
714//
715
716//
717// Symbols can turn into
718// - uniform/input reads
719// - output writes
720// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
721// - something simple that degenerates into the last bullet
722//
723void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
724{
725 // getSymbolId() will set up all the IO decorations on the first call.
726 // Formal function parameters were mapped during makeFunctions().
727 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700728
729 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
730 if (builder.isPointer(id)) {
731 spv::StorageClass sc = builder.getStorageClass(id);
732 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
733 iOSet.insert(id);
734 }
735
736 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700737 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600738 // Prepare to generate code for the access
739
740 // L-value chains will be computed left to right. We're on the symbol now,
741 // which is the left-most part of the access chain, so now is "clear" time,
742 // followed by setting the base.
743 builder.clearAccessChain();
744
745 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700746 // except for
747 // A) "const in" arguments to a function, which are an intermediate object.
748 // See comments in handleUserFunctionCall().
749 // B) Specialization constants (normal constant don't even come in as a variable),
750 // These are also pure R-values.
751 glslang::TQualifier qualifier = symbol->getQualifier();
752 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
753 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600754 builder.setAccessChainRValue(id);
755 else
756 builder.setAccessChainLValue(id);
757 }
758}
759
760bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
761{
762 // First, handle special cases
763 switch (node->getOp()) {
764 case glslang::EOpAssign:
765 case glslang::EOpAddAssign:
766 case glslang::EOpSubAssign:
767 case glslang::EOpMulAssign:
768 case glslang::EOpVectorTimesMatrixAssign:
769 case glslang::EOpVectorTimesScalarAssign:
770 case glslang::EOpMatrixTimesScalarAssign:
771 case glslang::EOpMatrixTimesMatrixAssign:
772 case glslang::EOpDivAssign:
773 case glslang::EOpModAssign:
774 case glslang::EOpAndAssign:
775 case glslang::EOpInclusiveOrAssign:
776 case glslang::EOpExclusiveOrAssign:
777 case glslang::EOpLeftShiftAssign:
778 case glslang::EOpRightShiftAssign:
779 // A bin-op assign "a += b" means the same thing as "a = a + b"
780 // where a is evaluated before b. For a simple assignment, GLSL
781 // says to evaluate the left before the right. So, always, left
782 // node then right node.
783 {
784 // get the left l-value, save it away
785 builder.clearAccessChain();
786 node->getLeft()->traverse(this);
787 spv::Builder::AccessChain lValue = builder.getAccessChain();
788
789 // evaluate the right
790 builder.clearAccessChain();
791 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700792 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600793
794 if (node->getOp() != glslang::EOpAssign) {
795 // the left is also an r-value
796 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700797 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600798
799 // do the operation
800 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
801 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
802 node->getType().getBasicType());
803
804 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700805 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600806 }
807
808 // store the result
809 builder.setAccessChain(lValue);
810 builder.accessChainStore(rValue);
811
812 // assignments are expressions having an rValue after they are evaluated...
813 builder.clearAccessChain();
814 builder.setAccessChainRValue(rValue);
815 }
816 return false;
817 case glslang::EOpIndexDirect:
818 case glslang::EOpIndexDirectStruct:
819 {
820 // Get the left part of the access chain.
821 node->getLeft()->traverse(this);
822
823 // Add the next element in the chain
824
John Kessenich55e7d112015-11-15 21:33:39 -0700825 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600826 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
827 // This may be, e.g., an anonymous block-member selection, which generally need
828 // index remapping due to hidden members in anonymous blocks.
829 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700830 assert(remapper.size() > 0);
831 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600832 }
833
834 if (! node->getLeft()->getType().isArray() &&
835 node->getLeft()->getType().isVector() &&
836 node->getOp() == glslang::EOpIndexDirect) {
837 // This is essentially a hard-coded vector swizzle of size 1,
838 // so short circuit the access-chain stuff with a swizzle.
839 std::vector<unsigned> swizzle;
840 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600841 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600842 } else {
843 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600844 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600845 }
846 }
847 return false;
848 case glslang::EOpIndexIndirect:
849 {
850 // Structure or array or vector indirection.
851 // Will use native SPIR-V access-chain for struct and array indirection;
852 // matrices are arrays of vectors, so will also work for a matrix.
853 // Will use the access chain's 'component' for variable index into a vector.
854
855 // This adapter is building access chains left to right.
856 // Set up the access chain to the left.
857 node->getLeft()->traverse(this);
858
859 // save it so that computing the right side doesn't trash it
860 spv::Builder::AccessChain partial = builder.getAccessChain();
861
862 // compute the next index in the chain
863 builder.clearAccessChain();
864 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700865 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600866
867 // restore the saved access chain
868 builder.setAccessChain(partial);
869
870 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600871 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600872 else
John Kessenichfa668da2015-09-13 14:46:30 -0600873 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600874 }
875 return false;
876 case glslang::EOpVectorSwizzle:
877 {
878 node->getLeft()->traverse(this);
879 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
880 std::vector<unsigned> swizzle;
881 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
882 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600883 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600884 }
885 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600886 case glslang::EOpLogicalOr:
887 case glslang::EOpLogicalAnd:
888 {
889
890 // These may require short circuiting, but can sometimes be done as straight
891 // binary operations. The right operand must be short circuited if it has
892 // side effects, and should probably be if it is complex.
893 if (isTrivial(node->getRight()->getAsTyped()))
894 break; // handle below as a normal binary operation
895 // otherwise, we need to do dynamic short circuiting on the right operand
896 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
897 builder.clearAccessChain();
898 builder.setAccessChainRValue(result);
899 }
900 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600901 default:
902 break;
903 }
904
905 // Assume generic binary op...
906
John Kessenich32cfd492016-02-02 12:37:46 -0700907 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600908 builder.clearAccessChain();
909 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700910 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600911
John Kessenich32cfd492016-02-02 12:37:46 -0700912 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600913 builder.clearAccessChain();
914 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700915 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600916
John Kessenich32cfd492016-02-02 12:37:46 -0700917 // get result
918 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
919 convertGlslangToSpvType(node->getType()), left, right,
920 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600921
John Kessenich50e57562015-12-21 21:21:11 -0700922 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600923 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700924 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700925 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600926 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600927 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600928 return false;
929 }
John Kessenich140f3df2015-06-26 16:58:36 -0600930}
931
932bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
933{
John Kessenichfc51d282015-08-19 13:34:18 -0600934 spv::Id result = spv::NoResult;
935
936 // try texturing first
937 result = createImageTextureFunctionCall(node);
938 if (result != spv::NoResult) {
939 builder.clearAccessChain();
940 builder.setAccessChainRValue(result);
941
942 return false; // done with this node
943 }
944
945 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600946
947 if (node->getOp() == glslang::EOpArrayLength) {
948 // Quite special; won't want to evaluate the operand.
949
950 // Normal .length() would have been constant folded by the front-end.
951 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600952 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600953 assert(node->getOperand()->getType().isRuntimeSizedArray());
954 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
955 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600956 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
957 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600958
959 builder.clearAccessChain();
960 builder.setAccessChainRValue(length);
961
962 return false;
963 }
964
John Kessenichfc51d282015-08-19 13:34:18 -0600965 // Start by evaluating the operand
966
John Kessenich140f3df2015-06-26 16:58:36 -0600967 builder.clearAccessChain();
968 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800969
Rex Xufc618912015-09-09 16:42:49 +0800970 spv::Id operand = spv::NoResult;
971
972 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
973 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800974 node->getOp() == glslang::EOpAtomicCounter ||
975 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800976 operand = builder.accessChainGetLValue(); // Special case l-value operands
977 else
John Kessenich32cfd492016-02-02 12:37:46 -0700978 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600979
980 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
981
982 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600983 if (! result)
984 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600985
986 // if not, then possibly an operation
987 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700988 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600989
990 if (result) {
991 builder.clearAccessChain();
992 builder.setAccessChainRValue(result);
993
994 return false; // done with this node
995 }
996
997 // it must be a special case, check...
998 switch (node->getOp()) {
999 case glslang::EOpPostIncrement:
1000 case glslang::EOpPostDecrement:
1001 case glslang::EOpPreIncrement:
1002 case glslang::EOpPreDecrement:
1003 {
1004 // we need the integer value "1" or the floating point "1.0" to add/subtract
1005 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
1006 builder.makeFloatConstant(1.0F) :
1007 builder.makeIntConstant(1);
1008 glslang::TOperator op;
1009 if (node->getOp() == glslang::EOpPreIncrement ||
1010 node->getOp() == glslang::EOpPostIncrement)
1011 op = glslang::EOpAdd;
1012 else
1013 op = glslang::EOpSub;
1014
1015 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1016 convertGlslangToSpvType(node->getType()), operand, one,
1017 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001018 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001019
1020 // The result of operation is always stored, but conditionally the
1021 // consumed result. The consumed result is always an r-value.
1022 builder.accessChainStore(result);
1023 builder.clearAccessChain();
1024 if (node->getOp() == glslang::EOpPreIncrement ||
1025 node->getOp() == glslang::EOpPreDecrement)
1026 builder.setAccessChainRValue(result);
1027 else
1028 builder.setAccessChainRValue(operand);
1029 }
1030
1031 return false;
1032
1033 case glslang::EOpEmitStreamVertex:
1034 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1035 return false;
1036 case glslang::EOpEndStreamPrimitive:
1037 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1038 return false;
1039
1040 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001041 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001042 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001043 }
John Kessenich140f3df2015-06-26 16:58:36 -06001044}
1045
1046bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1047{
John Kessenichfc51d282015-08-19 13:34:18 -06001048 spv::Id result = spv::NoResult;
1049
1050 // try texturing
1051 result = createImageTextureFunctionCall(node);
1052 if (result != spv::NoResult) {
1053 builder.clearAccessChain();
1054 builder.setAccessChainRValue(result);
1055
1056 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001057 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001058 // "imageStore" is a special case, which has no result
1059 return false;
1060 }
John Kessenichfc51d282015-08-19 13:34:18 -06001061
John Kessenich140f3df2015-06-26 16:58:36 -06001062 glslang::TOperator binOp = glslang::EOpNull;
1063 bool reduceComparison = true;
1064 bool isMatrix = false;
1065 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001066 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001067
1068 assert(node->getOp());
1069
1070 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1071
1072 switch (node->getOp()) {
1073 case glslang::EOpSequence:
1074 {
1075 if (preVisit)
1076 ++sequenceDepth;
1077 else
1078 --sequenceDepth;
1079
1080 if (sequenceDepth == 1) {
1081 // If this is the parent node of all the functions, we want to see them
1082 // early, so all call points have actual SPIR-V functions to reference.
1083 // In all cases, still let the traverser visit the children for us.
1084 makeFunctions(node->getAsAggregate()->getSequence());
1085
1086 // Also, we want all globals initializers to go into the entry of main(), before
1087 // anything else gets there, so visit out of order, doing them all now.
1088 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1089
1090 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1091 // so do them manually.
1092 visitFunctions(node->getAsAggregate()->getSequence());
1093
1094 return false;
1095 }
1096
1097 return true;
1098 }
1099 case glslang::EOpLinkerObjects:
1100 {
1101 if (visit == glslang::EvPreVisit)
1102 linkageOnly = true;
1103 else
1104 linkageOnly = false;
1105
1106 return true;
1107 }
1108 case glslang::EOpComma:
1109 {
1110 // processing from left to right naturally leaves the right-most
1111 // lying around in the access chain
1112 glslang::TIntermSequence& glslangOperands = node->getSequence();
1113 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1114 glslangOperands[i]->traverse(this);
1115
1116 return false;
1117 }
1118 case glslang::EOpFunction:
1119 if (visit == glslang::EvPreVisit) {
1120 if (isShaderEntrypoint(node)) {
1121 inMain = true;
1122 builder.setBuildPoint(shaderEntry->getLastBlock());
1123 } else {
1124 handleFunctionEntry(node);
1125 }
1126 } else {
1127 if (inMain)
1128 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001129 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001130 inMain = false;
1131 }
1132
1133 return true;
1134 case glslang::EOpParameters:
1135 // Parameters will have been consumed by EOpFunction processing, but not
1136 // the body, so we still visited the function node's children, making this
1137 // child redundant.
1138 return false;
1139 case glslang::EOpFunctionCall:
1140 {
1141 if (node->isUserDefined())
1142 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001143 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1144 if (result) {
1145 builder.clearAccessChain();
1146 builder.setAccessChainRValue(result);
1147 } else
1148 spv::MissingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001149
1150 return false;
1151 }
1152 case glslang::EOpConstructMat2x2:
1153 case glslang::EOpConstructMat2x3:
1154 case glslang::EOpConstructMat2x4:
1155 case glslang::EOpConstructMat3x2:
1156 case glslang::EOpConstructMat3x3:
1157 case glslang::EOpConstructMat3x4:
1158 case glslang::EOpConstructMat4x2:
1159 case glslang::EOpConstructMat4x3:
1160 case glslang::EOpConstructMat4x4:
1161 case glslang::EOpConstructDMat2x2:
1162 case glslang::EOpConstructDMat2x3:
1163 case glslang::EOpConstructDMat2x4:
1164 case glslang::EOpConstructDMat3x2:
1165 case glslang::EOpConstructDMat3x3:
1166 case glslang::EOpConstructDMat3x4:
1167 case glslang::EOpConstructDMat4x2:
1168 case glslang::EOpConstructDMat4x3:
1169 case glslang::EOpConstructDMat4x4:
1170 isMatrix = true;
1171 // fall through
1172 case glslang::EOpConstructFloat:
1173 case glslang::EOpConstructVec2:
1174 case glslang::EOpConstructVec3:
1175 case glslang::EOpConstructVec4:
1176 case glslang::EOpConstructDouble:
1177 case glslang::EOpConstructDVec2:
1178 case glslang::EOpConstructDVec3:
1179 case glslang::EOpConstructDVec4:
1180 case glslang::EOpConstructBool:
1181 case glslang::EOpConstructBVec2:
1182 case glslang::EOpConstructBVec3:
1183 case glslang::EOpConstructBVec4:
1184 case glslang::EOpConstructInt:
1185 case glslang::EOpConstructIVec2:
1186 case glslang::EOpConstructIVec3:
1187 case glslang::EOpConstructIVec4:
1188 case glslang::EOpConstructUint:
1189 case glslang::EOpConstructUVec2:
1190 case glslang::EOpConstructUVec3:
1191 case glslang::EOpConstructUVec4:
1192 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001193 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001194 {
1195 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001196 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001197 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1198 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001199 if (node->getOp() == glslang::EOpConstructTextureSampler)
1200 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1201 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001202 std::vector<spv::Id> constituents;
1203 for (int c = 0; c < (int)arguments.size(); ++c)
1204 constituents.push_back(arguments[c]);
1205 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001206 } else if (isMatrix)
1207 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1208 else
1209 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001210
1211 builder.clearAccessChain();
1212 builder.setAccessChainRValue(constructed);
1213
1214 return false;
1215 }
1216
1217 // These six are component-wise compares with component-wise results.
1218 // Forward on to createBinaryOperation(), requesting a vector result.
1219 case glslang::EOpLessThan:
1220 case glslang::EOpGreaterThan:
1221 case glslang::EOpLessThanEqual:
1222 case glslang::EOpGreaterThanEqual:
1223 case glslang::EOpVectorEqual:
1224 case glslang::EOpVectorNotEqual:
1225 {
1226 // Map the operation to a binary
1227 binOp = node->getOp();
1228 reduceComparison = false;
1229 switch (node->getOp()) {
1230 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1231 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1232 default: binOp = node->getOp(); break;
1233 }
1234
1235 break;
1236 }
1237 case glslang::EOpMul:
1238 // compontent-wise matrix multiply
1239 binOp = glslang::EOpMul;
1240 break;
1241 case glslang::EOpOuterProduct:
1242 // two vectors multiplied to make a matrix
1243 binOp = glslang::EOpOuterProduct;
1244 break;
1245 case glslang::EOpDot:
1246 {
1247 // for scalar dot product, use multiply
1248 glslang::TIntermSequence& glslangOperands = node->getSequence();
1249 if (! glslangOperands[0]->getAsTyped()->isVector())
1250 binOp = glslang::EOpMul;
1251 break;
1252 }
1253 case glslang::EOpMod:
1254 // when an aggregate, this is the floating-point mod built-in function,
1255 // which can be emitted by the one in createBinaryOperation()
1256 binOp = glslang::EOpMod;
1257 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001258 case glslang::EOpEmitVertex:
1259 case glslang::EOpEndPrimitive:
1260 case glslang::EOpBarrier:
1261 case glslang::EOpMemoryBarrier:
1262 case glslang::EOpMemoryBarrierAtomicCounter:
1263 case glslang::EOpMemoryBarrierBuffer:
1264 case glslang::EOpMemoryBarrierImage:
1265 case glslang::EOpMemoryBarrierShared:
1266 case glslang::EOpGroupMemoryBarrier:
1267 noReturnValue = true;
1268 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1269 break;
1270
John Kessenich426394d2015-07-23 10:22:48 -06001271 case glslang::EOpAtomicAdd:
1272 case glslang::EOpAtomicMin:
1273 case glslang::EOpAtomicMax:
1274 case glslang::EOpAtomicAnd:
1275 case glslang::EOpAtomicOr:
1276 case glslang::EOpAtomicXor:
1277 case glslang::EOpAtomicExchange:
1278 case glslang::EOpAtomicCompSwap:
1279 atomic = true;
1280 break;
1281
John Kessenich140f3df2015-06-26 16:58:36 -06001282 default:
1283 break;
1284 }
1285
1286 //
1287 // See if it maps to a regular operation.
1288 //
John Kessenich140f3df2015-06-26 16:58:36 -06001289 if (binOp != glslang::EOpNull) {
1290 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1291 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1292 assert(left && right);
1293
1294 builder.clearAccessChain();
1295 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001296 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001297
1298 builder.clearAccessChain();
1299 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001300 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001301
1302 result = createBinaryOperation(binOp, precision,
1303 convertGlslangToSpvType(node->getType()), leftId, rightId,
1304 left->getType().getBasicType(), reduceComparison);
1305
1306 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001307 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001308 builder.clearAccessChain();
1309 builder.setAccessChainRValue(result);
1310
1311 return false;
1312 }
1313
John Kessenich426394d2015-07-23 10:22:48 -06001314 //
1315 // Create the list of operands.
1316 //
John Kessenich140f3df2015-06-26 16:58:36 -06001317 glslang::TIntermSequence& glslangOperands = node->getSequence();
1318 std::vector<spv::Id> operands;
1319 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1320 builder.clearAccessChain();
1321 glslangOperands[arg]->traverse(this);
1322
1323 // special case l-value operands; there are just a few
1324 bool lvalue = false;
1325 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001326 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001327 case glslang::EOpModf:
1328 if (arg == 1)
1329 lvalue = true;
1330 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001331 case glslang::EOpInterpolateAtSample:
1332 case glslang::EOpInterpolateAtOffset:
1333 if (arg == 0)
1334 lvalue = true;
1335 break;
Rex Xud4782c12015-09-06 16:30:11 +08001336 case glslang::EOpAtomicAdd:
1337 case glslang::EOpAtomicMin:
1338 case glslang::EOpAtomicMax:
1339 case glslang::EOpAtomicAnd:
1340 case glslang::EOpAtomicOr:
1341 case glslang::EOpAtomicXor:
1342 case glslang::EOpAtomicExchange:
1343 case glslang::EOpAtomicCompSwap:
1344 if (arg == 0)
1345 lvalue = true;
1346 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001347 case glslang::EOpAddCarry:
1348 case glslang::EOpSubBorrow:
1349 if (arg == 2)
1350 lvalue = true;
1351 break;
1352 case glslang::EOpUMulExtended:
1353 case glslang::EOpIMulExtended:
1354 if (arg >= 2)
1355 lvalue = true;
1356 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001357 default:
1358 break;
1359 }
1360 if (lvalue)
1361 operands.push_back(builder.accessChainGetLValue());
1362 else
John Kessenich32cfd492016-02-02 12:37:46 -07001363 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001364 }
John Kessenich426394d2015-07-23 10:22:48 -06001365
1366 if (atomic) {
1367 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001368 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001369 } else {
1370 // Pass through to generic operations.
1371 switch (glslangOperands.size()) {
1372 case 0:
1373 result = createNoArgOperation(node->getOp());
1374 break;
1375 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001376 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001377 break;
1378 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001379 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001380 break;
1381 }
John Kessenich140f3df2015-06-26 16:58:36 -06001382 }
1383
1384 if (noReturnValue)
1385 return false;
1386
1387 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001388 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001389 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001390 } else {
1391 builder.clearAccessChain();
1392 builder.setAccessChainRValue(result);
1393 return false;
1394 }
1395}
1396
1397bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1398{
1399 // This path handles both if-then-else and ?:
1400 // The if-then-else has a node type of void, while
1401 // ?: has a non-void node type
1402 spv::Id result = 0;
1403 if (node->getBasicType() != glslang::EbtVoid) {
1404 // don't handle this as just on-the-fly temporaries, because there will be two names
1405 // and better to leave SSA to later passes
1406 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1407 }
1408
1409 // emit the condition before doing anything with selection
1410 node->getCondition()->traverse(this);
1411
1412 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001413 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001414
1415 if (node->getTrueBlock()) {
1416 // emit the "then" statement
1417 node->getTrueBlock()->traverse(this);
1418 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001419 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001420 }
1421
1422 if (node->getFalseBlock()) {
1423 ifBuilder.makeBeginElse();
1424 // emit the "else" statement
1425 node->getFalseBlock()->traverse(this);
1426 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001427 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001428 }
1429
1430 ifBuilder.makeEndIf();
1431
1432 if (result) {
1433 // GLSL only has r-values as the result of a :?, but
1434 // if we have an l-value, that can be more efficient if it will
1435 // become the base of a complex r-value expression, because the
1436 // next layer copies r-values into memory to use the access-chain mechanism
1437 builder.clearAccessChain();
1438 builder.setAccessChainLValue(result);
1439 }
1440
1441 return false;
1442}
1443
1444bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1445{
1446 // emit and get the condition before doing anything with switch
1447 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001448 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001449
1450 // browse the children to sort out code segments
1451 int defaultSegment = -1;
1452 std::vector<TIntermNode*> codeSegments;
1453 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1454 std::vector<int> caseValues;
1455 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1456 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1457 TIntermNode* child = *c;
1458 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001459 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001460 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001461 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001462 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1463 } else
1464 codeSegments.push_back(child);
1465 }
1466
1467 // handle the case where the last code segment is missing, due to no code
1468 // statements between the last case and the end of the switch statement
1469 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1470 (int)codeSegments.size() == defaultSegment)
1471 codeSegments.push_back(nullptr);
1472
1473 // make the switch statement
1474 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001475 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001476
1477 // emit all the code in the segments
1478 breakForLoop.push(false);
1479 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1480 builder.nextSwitchSegment(segmentBlocks, s);
1481 if (codeSegments[s])
1482 codeSegments[s]->traverse(this);
1483 else
1484 builder.addSwitchBreak();
1485 }
1486 breakForLoop.pop();
1487
1488 builder.endSwitch(segmentBlocks);
1489
1490 return false;
1491}
1492
1493void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1494{
1495 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001496 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001497
1498 builder.clearAccessChain();
1499 builder.setAccessChainRValue(constant);
1500}
1501
1502bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1503{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001504 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001505 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001506 // Spec requires back edges to target header blocks, and every header block
1507 // must dominate its merge block. Make a header block first to ensure these
1508 // conditions are met. By definition, it will contain OpLoopMerge, followed
1509 // by a block-ending branch. But we don't want to put any other body/test
1510 // instructions in it, since the body/test may have arbitrary instructions,
1511 // including merges of its own.
1512 builder.setBuildPoint(&blocks.head);
1513 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001514 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001515 spv::Block& test = builder.makeNewBlock();
1516 builder.createBranch(&test);
1517
1518 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001519 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001520 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001521 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001522 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1523
1524 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001525 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001526 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001527 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001528 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001529 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001530
1531 builder.setBuildPoint(&blocks.continue_target);
1532 if (node->getTerminal())
1533 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001534 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001535 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001536 builder.createBranch(&blocks.body);
1537
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001538 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001539 builder.setBuildPoint(&blocks.body);
1540 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001541 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001542 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001543 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001544
1545 builder.setBuildPoint(&blocks.continue_target);
1546 if (node->getTerminal())
1547 node->getTerminal()->traverse(this);
1548 if (node->getTest()) {
1549 node->getTest()->traverse(this);
1550 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001551 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001552 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001553 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001554 // TODO: unless there was a break/return/discard instruction
1555 // somewhere in the body, this is an infinite loop, so we should
1556 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001557 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001558 }
John Kessenich140f3df2015-06-26 16:58:36 -06001559 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001560 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001561 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001562 return false;
1563}
1564
1565bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1566{
1567 if (node->getExpression())
1568 node->getExpression()->traverse(this);
1569
1570 switch (node->getFlowOp()) {
1571 case glslang::EOpKill:
1572 builder.makeDiscard();
1573 break;
1574 case glslang::EOpBreak:
1575 if (breakForLoop.top())
1576 builder.createLoopExit();
1577 else
1578 builder.addSwitchBreak();
1579 break;
1580 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001581 builder.createLoopContinue();
1582 break;
1583 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001584 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001585 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001586 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001587 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001588
1589 builder.clearAccessChain();
1590 break;
1591
1592 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001593 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001594 break;
1595 }
1596
1597 return false;
1598}
1599
1600spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1601{
1602 // First, steer off constants, which are not SPIR-V variables, but
1603 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001604 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001605 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001606 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001607 }
1608
1609 // Now, handle actual variables
1610 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1611 spv::Id spvType = convertGlslangToSpvType(node->getType());
1612
1613 const char* name = node->getName().c_str();
1614 if (glslang::IsAnonymous(name))
1615 name = "";
1616
1617 return builder.createVariable(storageClass, spvType, name);
1618}
1619
1620// Return type Id of the sampled type.
1621spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1622{
1623 switch (sampler.type) {
1624 case glslang::EbtFloat: return builder.makeFloatType(32);
1625 case glslang::EbtInt: return builder.makeIntType(32);
1626 case glslang::EbtUint: return builder.makeUintType(32);
1627 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001628 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001629 return builder.makeFloatType(32);
1630 }
1631}
1632
John Kessenich3ac051e2015-12-20 11:29:16 -07001633// Convert from a glslang type to an SPV type, by calling into a
1634// recursive version of this function. This establishes the inherited
1635// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001636spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1637{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001638 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001639}
1640
1641// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001642// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001643spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001644{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001645 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001646
1647 switch (type.getBasicType()) {
1648 case glslang::EbtVoid:
1649 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001650 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001651 break;
1652 case glslang::EbtFloat:
1653 spvType = builder.makeFloatType(32);
1654 break;
1655 case glslang::EbtDouble:
1656 spvType = builder.makeFloatType(64);
1657 break;
1658 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001659 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1660 // a 32-bit int where non-0 means true.
1661 if (explicitLayout != glslang::ElpNone)
1662 spvType = builder.makeUintType(32);
1663 else
1664 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001665 break;
1666 case glslang::EbtInt:
1667 spvType = builder.makeIntType(32);
1668 break;
1669 case glslang::EbtUint:
1670 spvType = builder.makeUintType(32);
1671 break;
John Kessenich426394d2015-07-23 10:22:48 -06001672 case glslang::EbtAtomicUint:
1673 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1674 spvType = builder.makeUintType(32);
1675 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001676 case glslang::EbtSampler:
1677 {
1678 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001679 if (sampler.sampler) {
1680 // pure sampler
1681 spvType = builder.makeSamplerType();
1682 } else {
1683 // an image is present, make its type
1684 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1685 sampler.image ? 2 : 1, TranslateImageFormat(type));
1686 if (sampler.combined) {
1687 // already has both image and sampler, make the combined type
1688 spvType = builder.makeSampledImageType(spvType);
1689 }
John Kessenich55e7d112015-11-15 21:33:39 -07001690 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001691 }
John Kessenich140f3df2015-06-26 16:58:36 -06001692 break;
1693 case glslang::EbtStruct:
1694 case glslang::EbtBlock:
1695 {
1696 // If we've seen this struct type, return it
1697 const glslang::TTypeList* glslangStruct = type.getStruct();
1698 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001699
1700 // Try to share structs for different layouts, but not yet for other
1701 // kinds of qualification (primarily not yet including interpolant qualification).
1702 if (! HasNonLayoutQualifiers(qualifier))
1703 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1704 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001705 break;
1706
1707 // else, we haven't seen it...
1708
1709 // Create a vector of struct types for SPIR-V to consume
1710 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1711 if (type.getBasicType() == glslang::EbtBlock)
1712 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001713 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001714 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1715 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1716 if (glslangType.hiddenMember()) {
1717 ++memberDelta;
1718 if (type.getBasicType() == glslang::EbtBlock)
1719 memberRemapper[glslangStruct][i] = -1;
1720 } else {
1721 if (type.getBasicType() == glslang::EbtBlock)
1722 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001723 // modify just this child's view of the qualifier
1724 glslang::TQualifier subQualifier = glslangType.getQualifier();
1725 InheritQualifiers(subQualifier, qualifier);
John Kessenich7b9fa252016-01-21 18:56:57 -07001726 if (qualifier.hasLocation()) {
1727 subQualifier.layoutLocation += locationOffset;
1728 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1729 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001730 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001731 }
1732 }
1733
1734 // Make the SPIR-V type
1735 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001736 if (! HasNonLayoutQualifiers(qualifier))
1737 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001738
1739 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001740 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001741 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001742 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1743 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1744 int member = i;
1745 if (type.getBasicType() == glslang::EbtBlock)
1746 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001747
John Kesseniche0b6cad2015-12-24 10:30:13 -07001748 // modify just this child's view of the qualifier
1749 glslang::TQualifier subQualifier = glslangType.getQualifier();
1750 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001751
John Kessenich140f3df2015-06-26 16:58:36 -06001752 // using -1 above to indicate a hidden member
1753 if (member >= 0) {
1754 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001755 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001756 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001757 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1758 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich7b9fa252016-01-21 18:56:57 -07001759 if (qualifier.hasLocation()) {
1760 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, qualifier.layoutLocation + locationOffset);
1761 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1762 }
John Kessenich140f3df2015-06-26 16:58:36 -06001763 if (glslangType.getQualifier().hasComponent())
1764 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1765 if (glslangType.getQualifier().hasXfbOffset())
1766 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001767 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001768 // figure out what to do with offset, which is accumulating
1769 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001770 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001771 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001772 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001773 offset = nextOffset;
1774 }
John Kessenich140f3df2015-06-26 16:58:36 -06001775
John Kessenichf85e8062015-12-19 13:57:10 -07001776 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001777 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001778
John Kessenich140f3df2015-06-26 16:58:36 -06001779 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001780 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1781 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001782 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001783 }
1784 }
1785
1786 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001787 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001788 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenich92187592016-02-01 13:45:25 -07001789 if (type.getQualifier().hasStream()) {
1790 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001791 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001792 }
John Kessenich140f3df2015-06-26 16:58:36 -06001793 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001794 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001795 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001796 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001797 if (type.getQualifier().hasXfbBuffer())
1798 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1799 }
1800 }
1801 break;
1802 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001803 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001804 break;
1805 }
1806
1807 if (type.isMatrix())
1808 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1809 else {
1810 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1811 if (type.getVectorSize() > 1)
1812 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1813 }
1814
1815 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001816 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1817
John Kessenichc9a80832015-09-12 12:17:44 -06001818 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001819 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001820 // We need to decorate array strides for types needing explicit layout, except blocks.
1821 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001822 // Use a dummy glslang type for querying internal strides of
1823 // arrays of arrays, but using just a one-dimensional array.
1824 glslang::TType simpleArrayType(type, 0); // deference type of the array
1825 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1826 simpleArrayType.getArraySizes().dereference();
1827
1828 // Will compute the higher-order strides here, rather than making a whole
1829 // pile of types and doing repetitive recursion on their contents.
1830 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1831 }
John Kessenichf8842e52016-01-04 19:22:56 -07001832
1833 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001834 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001835 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001836 if (stride > 0)
1837 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001838 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001839 }
1840 } else {
1841 // single-dimensional array, and don't yet have stride
1842
John Kessenichf8842e52016-01-04 19:22:56 -07001843 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001844 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1845 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001846 }
John Kessenich31ed4832015-09-09 17:51:38 -06001847
John Kessenichc9a80832015-09-12 12:17:44 -06001848 // Do the outer dimension, which might not be known for a runtime-sized array
1849 if (type.isRuntimeSizedArray()) {
1850 spvType = builder.makeRuntimeArray(spvType);
1851 } else {
1852 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001853 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001854 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001855 if (stride > 0)
1856 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001857 }
1858
1859 return spvType;
1860}
1861
John Kessenich6c292d32016-02-15 20:58:50 -07001862// Turn the expression forming the array size into an id.
1863// This is not quite trivial, because of specialization constants.
1864// Sometimes, a raw constant is turned into an Id, and sometimes
1865// a specialization constant expression is.
1866spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1867{
1868 // First, see if this is sized with a node, meaning a specialization constant:
1869 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1870 if (specNode != nullptr) {
1871 builder.clearAccessChain();
1872 specNode->traverse(this);
1873 return accessChainLoad(specNode->getAsTyped()->getType());
1874 }
1875
1876 // Otherwise, need a compile-time (front end) size, get it:
1877 int size = arraySizes.getDimSize(dim);
1878 assert(size > 0);
1879 return builder.makeUintConstant(size);
1880}
1881
John Kessenich103bef92016-02-08 21:38:15 -07001882// Wrap the builder's accessChainLoad to:
1883// - localize handling of RelaxedPrecision
1884// - use the SPIR-V inferred type instead of another conversion of the glslang type
1885// (avoids unnecessary work and possible type punning for structures)
1886// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001887spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1888{
John Kessenich103bef92016-02-08 21:38:15 -07001889 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1890 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1891
1892 // Need to convert to abstract types when necessary
1893 if (builder.isScalarType(nominalTypeId) && type.getBasicType() == glslang::EbtBool && nominalTypeId != builder.makeBoolType())
1894 loadedId = builder.createBinOp(spv::OpINotEqual, builder.makeBoolType(), loadedId, builder.makeUintConstant(0));
1895
1896 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07001897}
1898
John Kessenichf85e8062015-12-19 13:57:10 -07001899// Decide whether or not this type should be
1900// decorated with offsets and strides, and if so
1901// whether std140 or std430 rules should be applied.
1902glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001903{
John Kessenichf85e8062015-12-19 13:57:10 -07001904 // has to be a block
1905 if (type.getBasicType() != glslang::EbtBlock)
1906 return glslang::ElpNone;
1907
1908 // has to be a uniform or buffer block
1909 if (type.getQualifier().storage != glslang::EvqUniform &&
1910 type.getQualifier().storage != glslang::EvqBuffer)
1911 return glslang::ElpNone;
1912
1913 // return the layout to use
1914 switch (type.getQualifier().layoutPacking) {
1915 case glslang::ElpStd140:
1916 case glslang::ElpStd430:
1917 return type.getQualifier().layoutPacking;
1918 default:
1919 return glslang::ElpNone;
1920 }
John Kessenich31ed4832015-09-09 17:51:38 -06001921}
1922
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001923// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001924int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001925{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001926 int size;
John Kessenich49987892015-12-29 17:11:44 -07001927 int stride;
1928 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001929
1930 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001931}
1932
John Kessenich49987892015-12-29 17:11:44 -07001933// 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 -07001934// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001935int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001936{
John Kessenich49987892015-12-29 17:11:44 -07001937 glslang::TType elementType;
1938 elementType.shallowCopy(matrixType);
1939 elementType.clearArraySizes();
1940
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001941 int size;
John Kessenich49987892015-12-29 17:11:44 -07001942 int stride;
1943 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
1944
1945 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001946}
1947
John Kessenich5e4b1242015-08-06 22:53:06 -06001948// Given a member type of a struct, realign the current offset for it, and compute
1949// the next (not yet aligned) offset for the next member, which will get aligned
1950// on the next call.
1951// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1952// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1953// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07001954void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07001955 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06001956{
1957 // this will get a positive value when deemed necessary
1958 nextOffset = -1;
1959
John Kessenich5e4b1242015-08-06 22:53:06 -06001960 // override anything in currentOffset with user-set offset
1961 if (memberType.getQualifier().hasOffset())
1962 currentOffset = memberType.getQualifier().layoutOffset;
1963
1964 // It could be that current linker usage in glslang updated all the layoutOffset,
1965 // in which case the following code does not matter. But, that's not quite right
1966 // once cross-compilation unit GLSL validation is done, as the original user
1967 // settings are needed in layoutOffset, and then the following will come into play.
1968
John Kessenichf85e8062015-12-19 13:57:10 -07001969 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001970 if (! memberType.getQualifier().hasOffset())
1971 currentOffset = -1;
1972
1973 return;
1974 }
1975
John Kessenichf85e8062015-12-19 13:57:10 -07001976 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06001977 if (currentOffset < 0)
1978 currentOffset = 0;
1979
1980 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1981 // but possibly not yet correctly aligned.
1982
1983 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07001984 int dummyStride;
1985 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06001986 glslang::RoundToPow2(currentOffset, memberAlignment);
1987 nextOffset = currentOffset + memberSize;
1988}
1989
John Kessenich140f3df2015-06-26 16:58:36 -06001990bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1991{
1992 return node->getName() == "main(";
1993}
1994
1995// Make all the functions, skeletally, without actually visiting their bodies.
1996void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1997{
1998 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1999 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2000 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2001 continue;
2002
2003 // We're on a user function. Set up the basic interface for the function now,
2004 // so that it's available to call.
2005 // Translating the body will happen later.
2006 //
2007 // Typically (except for a "const in" parameter), an address will be passed to the
2008 // function. What it is an address of varies:
2009 //
2010 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2011 // so that write needs to be to a copy, hence the address of a copy works.
2012 //
2013 // - "const in" parameters can just be the r-value, as no writes need occur.
2014 //
2015 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2016 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2017
2018 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002019 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002020 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2021
2022 for (int p = 0; p < (int)parameters.size(); ++p) {
2023 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2024 spv::Id typeId = convertGlslangToSpvType(paramType);
2025 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2026 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2027 else
2028 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002029 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002030 paramTypes.push_back(typeId);
2031 }
2032
2033 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002034 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2035 convertGlslangToSpvType(glslFunction->getType()),
2036 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002037
2038 // Track function to emit/call later
2039 functionMap[glslFunction->getName().c_str()] = function;
2040
2041 // Set the parameter id's
2042 for (int p = 0; p < (int)parameters.size(); ++p) {
2043 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2044 // give a name too
2045 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2046 }
2047 }
2048}
2049
2050// Process all the initializers, while skipping the functions and link objects
2051void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2052{
2053 builder.setBuildPoint(shaderEntry->getLastBlock());
2054 for (int i = 0; i < (int)initializers.size(); ++i) {
2055 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2056 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2057
2058 // We're on a top-level node that's not a function. Treat as an initializer, whose
2059 // code goes into the beginning of main.
2060 initializer->traverse(this);
2061 }
2062 }
2063}
2064
2065// Process all the functions, while skipping initializers.
2066void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2067{
2068 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2069 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2070 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2071 node->traverse(this);
2072 }
2073}
2074
2075void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2076{
2077 // SPIR-V functions should already be in the functionMap from the prepass
2078 // that called makeFunctions().
2079 spv::Function* function = functionMap[node->getName().c_str()];
2080 spv::Block* functionBlock = function->getEntryBlock();
2081 builder.setBuildPoint(functionBlock);
2082}
2083
Rex Xu04db3f52015-09-16 11:44:02 +08002084void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002085{
Rex Xufc618912015-09-09 16:42:49 +08002086 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002087
2088 glslang::TSampler sampler = {};
2089 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002090 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002091 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2092 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2093 }
2094
John Kessenich140f3df2015-06-26 16:58:36 -06002095 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2096 builder.clearAccessChain();
2097 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002098
2099 // Special case l-value operands
2100 bool lvalue = false;
2101 switch (node.getOp()) {
2102 case glslang::EOpImageAtomicAdd:
2103 case glslang::EOpImageAtomicMin:
2104 case glslang::EOpImageAtomicMax:
2105 case glslang::EOpImageAtomicAnd:
2106 case glslang::EOpImageAtomicOr:
2107 case glslang::EOpImageAtomicXor:
2108 case glslang::EOpImageAtomicExchange:
2109 case glslang::EOpImageAtomicCompSwap:
2110 if (i == 0)
2111 lvalue = true;
2112 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002113 case glslang::EOpSparseImageLoad:
2114 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2115 lvalue = true;
2116 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002117 case glslang::EOpSparseTexture:
2118 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2119 lvalue = true;
2120 break;
2121 case glslang::EOpSparseTextureClamp:
2122 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2123 lvalue = true;
2124 break;
2125 case glslang::EOpSparseTextureLod:
2126 case glslang::EOpSparseTextureOffset:
2127 if (i == 3)
2128 lvalue = true;
2129 break;
2130 case glslang::EOpSparseTextureFetch:
2131 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2132 lvalue = true;
2133 break;
2134 case glslang::EOpSparseTextureFetchOffset:
2135 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2136 lvalue = true;
2137 break;
2138 case glslang::EOpSparseTextureLodOffset:
2139 case glslang::EOpSparseTextureGrad:
2140 case glslang::EOpSparseTextureOffsetClamp:
2141 if (i == 4)
2142 lvalue = true;
2143 break;
2144 case glslang::EOpSparseTextureGradOffset:
2145 case glslang::EOpSparseTextureGradClamp:
2146 if (i == 5)
2147 lvalue = true;
2148 break;
2149 case glslang::EOpSparseTextureGradOffsetClamp:
2150 if (i == 6)
2151 lvalue = true;
2152 break;
2153 case glslang::EOpSparseTextureGather:
2154 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2155 lvalue = true;
2156 break;
2157 case glslang::EOpSparseTextureGatherOffset:
2158 case glslang::EOpSparseTextureGatherOffsets:
2159 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2160 lvalue = true;
2161 break;
Rex Xufc618912015-09-09 16:42:49 +08002162 default:
2163 break;
2164 }
2165
Rex Xu6b86d492015-09-16 17:48:22 +08002166 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002167 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002168 else
John Kessenich32cfd492016-02-02 12:37:46 -07002169 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002170 }
2171}
2172
John Kessenichfc51d282015-08-19 13:34:18 -06002173void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002174{
John Kessenichfc51d282015-08-19 13:34:18 -06002175 builder.clearAccessChain();
2176 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002177 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002178}
John Kessenich140f3df2015-06-26 16:58:36 -06002179
John Kessenichfc51d282015-08-19 13:34:18 -06002180spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2181{
Rex Xufc618912015-09-09 16:42:49 +08002182 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002183 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002184 }
2185
John Kessenichfc51d282015-08-19 13:34:18 -06002186 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002187 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2188 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2189 std::vector<spv::Id> arguments;
2190 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002191 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002192 else
2193 translateArguments(*node->getAsUnaryNode(), arguments);
2194 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2195
2196 spv::Builder::TextureParameters params = { };
2197 params.sampler = arguments[0];
2198
Rex Xu04db3f52015-09-16 11:44:02 +08002199 glslang::TCrackedTextureOp cracked;
2200 node->crackTexture(sampler, cracked);
2201
John Kessenichfc51d282015-08-19 13:34:18 -06002202 // Check for queries
2203 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002204 // a sampled image needs to have the image extracted first
2205 if (builder.isSampledImage(params.sampler))
2206 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002207 switch (node->getOp()) {
2208 case glslang::EOpImageQuerySize:
2209 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002210 if (arguments.size() > 1) {
2211 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002212 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002213 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002214 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002215 case glslang::EOpImageQuerySamples:
2216 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002217 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002218 case glslang::EOpTextureQueryLod:
2219 params.coords = arguments[1];
2220 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2221 case glslang::EOpTextureQueryLevels:
2222 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002223 case glslang::EOpSparseTexelsResident:
2224 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002225 default:
2226 assert(0);
2227 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002228 }
John Kessenich140f3df2015-06-26 16:58:36 -06002229 }
2230
Rex Xufc618912015-09-09 16:42:49 +08002231 // Check for image functions other than queries
2232 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002233 std::vector<spv::Id> operands;
2234 auto opIt = arguments.begin();
2235 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002236
2237 // Handle subpass operations
2238 // TODO: GLSL should change to have the "MS" only on the type rather than the
2239 // built-in function.
2240 if (cracked.subpass) {
2241 // add on the (0,0) coordinate
2242 spv::Id zero = builder.makeIntConstant(0);
2243 std::vector<spv::Id> comps;
2244 comps.push_back(zero);
2245 comps.push_back(zero);
2246 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2247 if (sampler.ms) {
2248 operands.push_back(spv::ImageOperandsSampleMask);
2249 operands.push_back(*(opIt++));
2250 }
2251 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2252 }
2253
John Kessenich56bab042015-09-16 10:54:31 -06002254 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002255 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002256 if (sampler.ms) {
2257 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002258 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002259 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002260 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2261 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002262 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002263 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002264 if (sampler.ms) {
2265 operands.push_back(*(opIt + 1));
2266 operands.push_back(spv::ImageOperandsSampleMask);
2267 operands.push_back(*opIt);
2268 } else
2269 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002270 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002271 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2272 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002273 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002274 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2275 builder.addCapability(spv::CapabilitySparseResidency);
2276 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2277 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2278
2279 if (sampler.ms) {
2280 operands.push_back(spv::ImageOperandsSampleMask);
2281 operands.push_back(*opIt++);
2282 }
2283
2284 // Create the return type that was a special structure
2285 spv::Id texelOut = *opIt;
2286 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2287 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2288 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2289
2290 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2291
2292 // Decode the return type
2293 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2294 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002295 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002296 // Process image atomic operations
2297
2298 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2299 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002300 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002301
Rex Xufc618912015-09-09 16:42:49 +08002302 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002303 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002304
2305 std::vector<spv::Id> operands;
2306 operands.push_back(pointer);
2307 for (; opIt != arguments.end(); ++opIt)
2308 operands.push_back(*opIt);
2309
Rex Xu04db3f52015-09-16 11:44:02 +08002310 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002311 }
2312 }
2313
2314 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002315 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002316 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2317
John Kessenichfc51d282015-08-19 13:34:18 -06002318 // check for bias argument
2319 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002320 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002321 int nonBiasArgCount = 2;
2322 if (cracked.offset)
2323 ++nonBiasArgCount;
2324 if (cracked.grad)
2325 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002326 if (cracked.lodClamp)
2327 ++nonBiasArgCount;
2328 if (sparse)
2329 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002330
2331 if ((int)arguments.size() > nonBiasArgCount)
2332 bias = true;
2333 }
2334
John Kessenichfc51d282015-08-19 13:34:18 -06002335 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002336
John Kessenichfc51d282015-08-19 13:34:18 -06002337 params.coords = arguments[1];
2338 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002339 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002340
2341 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002342 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002343 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002344 ++extraArgs;
2345 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002346 params.Dref = arguments[2];
2347 ++extraArgs;
2348 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002349 std::vector<spv::Id> indexes;
2350 int comp;
2351 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002352 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002353 else
2354 comp = builder.getNumComponents(params.coords) - 1;
2355 indexes.push_back(comp);
2356 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2357 }
2358 if (cracked.lod) {
2359 params.lod = arguments[2];
2360 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002361 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2362 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2363 noImplicitLod = true;
2364 }
2365 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002366 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002367 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002368 }
2369 if (cracked.grad) {
2370 params.gradX = arguments[2 + extraArgs];
2371 params.gradY = arguments[3 + extraArgs];
2372 extraArgs += 2;
2373 }
John Kessenich55e7d112015-11-15 21:33:39 -07002374 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002375 params.offset = arguments[2 + extraArgs];
2376 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002377 } else if (cracked.offsets) {
2378 params.offsets = arguments[2 + extraArgs];
2379 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002380 }
Rex Xu48edadf2015-12-31 16:11:41 +08002381 if (cracked.lodClamp) {
2382 params.lodClamp = arguments[2 + extraArgs];
2383 ++extraArgs;
2384 }
2385 if (sparse) {
2386 params.texelOut = arguments[2 + extraArgs];
2387 ++extraArgs;
2388 }
John Kessenichfc51d282015-08-19 13:34:18 -06002389 if (bias) {
2390 params.bias = arguments[2 + extraArgs];
2391 ++extraArgs;
2392 }
John Kessenich55e7d112015-11-15 21:33:39 -07002393 if (cracked.gather && ! sampler.shadow) {
2394 // default component is 0, if missing, otherwise an argument
2395 if (2 + extraArgs < (int)arguments.size()) {
2396 params.comp = arguments[2 + extraArgs];
2397 ++extraArgs;
2398 } else {
2399 params.comp = builder.makeIntConstant(0);
2400 }
2401 }
John Kessenichfc51d282015-08-19 13:34:18 -06002402
John Kessenich019f08f2016-02-15 15:40:42 -07002403 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002404}
2405
2406spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2407{
2408 // Grab the function's pointer from the previously created function
2409 spv::Function* function = functionMap[node->getName().c_str()];
2410 if (! function)
2411 return 0;
2412
2413 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2414 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2415
2416 // See comments in makeFunctions() for details about the semantics for parameter passing.
2417 //
2418 // These imply we need a four step process:
2419 // 1. Evaluate the arguments
2420 // 2. Allocate and make copies of in, out, and inout arguments
2421 // 3. Make the call
2422 // 4. Copy back the results
2423
2424 // 1. Evaluate the arguments
2425 std::vector<spv::Builder::AccessChain> lValues;
2426 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002427 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002428 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2429 // build l-value
2430 builder.clearAccessChain();
2431 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002432 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002433 // keep outputs as l-values, evaluate input-only as r-values
2434 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2435 // save l-value
2436 lValues.push_back(builder.getAccessChain());
2437 } else {
2438 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002439 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002440 }
2441 }
2442
2443 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2444 // copy the original into that space.
2445 //
2446 // Also, build up the list of actual arguments to pass in for the call
2447 int lValueCount = 0;
2448 int rValueCount = 0;
2449 std::vector<spv::Id> spvArgs;
2450 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2451 spv::Id arg;
2452 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2453 // need space to hold the copy
2454 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2455 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2456 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2457 // need to copy the input into output space
2458 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002459 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002460 builder.createStore(copy, arg);
2461 }
2462 ++lValueCount;
2463 } else {
2464 arg = rValues[rValueCount];
2465 ++rValueCount;
2466 }
2467 spvArgs.push_back(arg);
2468 }
2469
2470 // 3. Make the call.
2471 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002472 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002473
2474 // 4. Copy back out an "out" arguments.
2475 lValueCount = 0;
2476 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2477 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2478 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2479 spv::Id copy = builder.createLoad(spvArgs[a]);
2480 builder.setAccessChain(lValues[lValueCount]);
2481 builder.accessChainStore(copy);
2482 }
2483 ++lValueCount;
2484 }
2485 }
2486
2487 return result;
2488}
2489
2490// Translate AST operation to SPV operation, already having SPV-based operands/types.
2491spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2492 spv::Id typeId, spv::Id left, spv::Id right,
2493 glslang::TBasicType typeProxy, bool reduceComparison)
2494{
2495 bool isUnsigned = typeProxy == glslang::EbtUint;
2496 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2497
2498 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002499 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002500 bool comparison = false;
2501
2502 switch (op) {
2503 case glslang::EOpAdd:
2504 case glslang::EOpAddAssign:
2505 if (isFloat)
2506 binOp = spv::OpFAdd;
2507 else
2508 binOp = spv::OpIAdd;
2509 break;
2510 case glslang::EOpSub:
2511 case glslang::EOpSubAssign:
2512 if (isFloat)
2513 binOp = spv::OpFSub;
2514 else
2515 binOp = spv::OpISub;
2516 break;
2517 case glslang::EOpMul:
2518 case glslang::EOpMulAssign:
2519 if (isFloat)
2520 binOp = spv::OpFMul;
2521 else
2522 binOp = spv::OpIMul;
2523 break;
2524 case glslang::EOpVectorTimesScalar:
2525 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002526 if (isFloat) {
2527 if (builder.isVector(right))
2528 std::swap(left, right);
2529 assert(builder.isScalar(right));
2530 needMatchingVectors = false;
2531 binOp = spv::OpVectorTimesScalar;
2532 } else
2533 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002534 break;
2535 case glslang::EOpVectorTimesMatrix:
2536 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002537 binOp = spv::OpVectorTimesMatrix;
2538 break;
2539 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002540 binOp = spv::OpMatrixTimesVector;
2541 break;
2542 case glslang::EOpMatrixTimesScalar:
2543 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002544 binOp = spv::OpMatrixTimesScalar;
2545 break;
2546 case glslang::EOpMatrixTimesMatrix:
2547 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002548 binOp = spv::OpMatrixTimesMatrix;
2549 break;
2550 case glslang::EOpOuterProduct:
2551 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002552 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002553 break;
2554
2555 case glslang::EOpDiv:
2556 case glslang::EOpDivAssign:
2557 if (isFloat)
2558 binOp = spv::OpFDiv;
2559 else if (isUnsigned)
2560 binOp = spv::OpUDiv;
2561 else
2562 binOp = spv::OpSDiv;
2563 break;
2564 case glslang::EOpMod:
2565 case glslang::EOpModAssign:
2566 if (isFloat)
2567 binOp = spv::OpFMod;
2568 else if (isUnsigned)
2569 binOp = spv::OpUMod;
2570 else
2571 binOp = spv::OpSMod;
2572 break;
2573 case glslang::EOpRightShift:
2574 case glslang::EOpRightShiftAssign:
2575 if (isUnsigned)
2576 binOp = spv::OpShiftRightLogical;
2577 else
2578 binOp = spv::OpShiftRightArithmetic;
2579 break;
2580 case glslang::EOpLeftShift:
2581 case glslang::EOpLeftShiftAssign:
2582 binOp = spv::OpShiftLeftLogical;
2583 break;
2584 case glslang::EOpAnd:
2585 case glslang::EOpAndAssign:
2586 binOp = spv::OpBitwiseAnd;
2587 break;
2588 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002589 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002590 binOp = spv::OpLogicalAnd;
2591 break;
2592 case glslang::EOpInclusiveOr:
2593 case glslang::EOpInclusiveOrAssign:
2594 binOp = spv::OpBitwiseOr;
2595 break;
2596 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002597 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002598 binOp = spv::OpLogicalOr;
2599 break;
2600 case glslang::EOpExclusiveOr:
2601 case glslang::EOpExclusiveOrAssign:
2602 binOp = spv::OpBitwiseXor;
2603 break;
2604 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002605 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002606 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002607 break;
2608
2609 case glslang::EOpLessThan:
2610 case glslang::EOpGreaterThan:
2611 case glslang::EOpLessThanEqual:
2612 case glslang::EOpGreaterThanEqual:
2613 case glslang::EOpEqual:
2614 case glslang::EOpNotEqual:
2615 case glslang::EOpVectorEqual:
2616 case glslang::EOpVectorNotEqual:
2617 comparison = true;
2618 break;
2619 default:
2620 break;
2621 }
2622
John Kessenich7c1aa102015-10-15 13:29:11 -06002623 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002624 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002625 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002626 if (builder.isMatrix(left) || builder.isMatrix(right))
2627 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002628
2629 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002630 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002631 builder.promoteScalar(precision, left, right);
2632
John Kessenich32cfd492016-02-02 12:37:46 -07002633 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002634 }
2635
2636 if (! comparison)
2637 return 0;
2638
John Kessenich7c1aa102015-10-15 13:29:11 -06002639 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002640
2641 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2642 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2643
John Kessenich22118352015-12-21 20:54:09 -07002644 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002645 }
2646
2647 switch (op) {
2648 case glslang::EOpLessThan:
2649 if (isFloat)
2650 binOp = spv::OpFOrdLessThan;
2651 else if (isUnsigned)
2652 binOp = spv::OpULessThan;
2653 else
2654 binOp = spv::OpSLessThan;
2655 break;
2656 case glslang::EOpGreaterThan:
2657 if (isFloat)
2658 binOp = spv::OpFOrdGreaterThan;
2659 else if (isUnsigned)
2660 binOp = spv::OpUGreaterThan;
2661 else
2662 binOp = spv::OpSGreaterThan;
2663 break;
2664 case glslang::EOpLessThanEqual:
2665 if (isFloat)
2666 binOp = spv::OpFOrdLessThanEqual;
2667 else if (isUnsigned)
2668 binOp = spv::OpULessThanEqual;
2669 else
2670 binOp = spv::OpSLessThanEqual;
2671 break;
2672 case glslang::EOpGreaterThanEqual:
2673 if (isFloat)
2674 binOp = spv::OpFOrdGreaterThanEqual;
2675 else if (isUnsigned)
2676 binOp = spv::OpUGreaterThanEqual;
2677 else
2678 binOp = spv::OpSGreaterThanEqual;
2679 break;
2680 case glslang::EOpEqual:
2681 case glslang::EOpVectorEqual:
2682 if (isFloat)
2683 binOp = spv::OpFOrdEqual;
2684 else
2685 binOp = spv::OpIEqual;
2686 break;
2687 case glslang::EOpNotEqual:
2688 case glslang::EOpVectorNotEqual:
2689 if (isFloat)
2690 binOp = spv::OpFOrdNotEqual;
2691 else
2692 binOp = spv::OpINotEqual;
2693 break;
2694 default:
2695 break;
2696 }
2697
John Kessenich32cfd492016-02-02 12:37:46 -07002698 if (binOp != spv::OpNop)
2699 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002700
2701 return 0;
2702}
2703
John Kessenich04bb8a02015-12-12 12:28:14 -07002704//
2705// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2706// These can be any of:
2707//
2708// matrix * scalar
2709// scalar * matrix
2710// matrix * matrix linear algebraic
2711// matrix * vector
2712// vector * matrix
2713// matrix * matrix componentwise
2714// matrix op matrix op in {+, -, /}
2715// matrix op scalar op in {+, -, /}
2716// scalar op matrix op in {+, -, /}
2717//
2718spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2719{
2720 bool firstClass = true;
2721
2722 // First, handle first-class matrix operations (* and matrix/scalar)
2723 switch (op) {
2724 case spv::OpFDiv:
2725 if (builder.isMatrix(left) && builder.isScalar(right)) {
2726 // turn matrix / scalar into a multiply...
2727 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2728 op = spv::OpMatrixTimesScalar;
2729 } else
2730 firstClass = false;
2731 break;
2732 case spv::OpMatrixTimesScalar:
2733 if (builder.isMatrix(right))
2734 std::swap(left, right);
2735 assert(builder.isScalar(right));
2736 break;
2737 case spv::OpVectorTimesMatrix:
2738 assert(builder.isVector(left));
2739 assert(builder.isMatrix(right));
2740 break;
2741 case spv::OpMatrixTimesVector:
2742 assert(builder.isMatrix(left));
2743 assert(builder.isVector(right));
2744 break;
2745 case spv::OpMatrixTimesMatrix:
2746 assert(builder.isMatrix(left));
2747 assert(builder.isMatrix(right));
2748 break;
2749 default:
2750 firstClass = false;
2751 break;
2752 }
2753
John Kessenich32cfd492016-02-02 12:37:46 -07002754 if (firstClass)
2755 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002756
2757 // Handle component-wise +, -, *, and / for all combinations of type.
2758 // The result type of all of them is the same type as the (a) matrix operand.
2759 // The algorithm is to:
2760 // - break the matrix(es) into vectors
2761 // - smear any scalar to a vector
2762 // - do vector operations
2763 // - make a matrix out the vector results
2764 switch (op) {
2765 case spv::OpFAdd:
2766 case spv::OpFSub:
2767 case spv::OpFDiv:
2768 case spv::OpFMul:
2769 {
2770 // one time set up...
2771 bool leftMat = builder.isMatrix(left);
2772 bool rightMat = builder.isMatrix(right);
2773 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2774 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2775 spv::Id scalarType = builder.getScalarTypeId(typeId);
2776 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2777 std::vector<spv::Id> results;
2778 spv::Id smearVec = spv::NoResult;
2779 if (builder.isScalar(left))
2780 smearVec = builder.smearScalar(precision, left, vecType);
2781 else if (builder.isScalar(right))
2782 smearVec = builder.smearScalar(precision, right, vecType);
2783
2784 // do each vector op
2785 for (unsigned int c = 0; c < numCols; ++c) {
2786 std::vector<unsigned int> indexes;
2787 indexes.push_back(c);
2788 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2789 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2790 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2791 builder.setPrecision(results.back(), precision);
2792 }
2793
2794 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002795 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002796 }
2797 default:
2798 assert(0);
2799 return spv::NoResult;
2800 }
2801}
2802
Rex Xu04db3f52015-09-16 11:44:02 +08002803spv::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 -06002804{
2805 spv::Op unaryOp = spv::OpNop;
2806 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002807 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002808 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002809
2810 switch (op) {
2811 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002812 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002813 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002814 if (builder.isMatrixType(typeId))
2815 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2816 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002817 unaryOp = spv::OpSNegate;
2818 break;
2819
2820 case glslang::EOpLogicalNot:
2821 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002822 unaryOp = spv::OpLogicalNot;
2823 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002824 case glslang::EOpBitwiseNot:
2825 unaryOp = spv::OpNot;
2826 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002827
John Kessenich140f3df2015-06-26 16:58:36 -06002828 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002829 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002830 break;
2831 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002832 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002833 break;
2834 case glslang::EOpTranspose:
2835 unaryOp = spv::OpTranspose;
2836 break;
2837
2838 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002839 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002840 break;
2841 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002842 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002843 break;
2844 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002845 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002846 break;
2847 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002848 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002849 break;
2850 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002851 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002852 break;
2853 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002854 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002855 break;
2856 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002857 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002858 break;
2859 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002860 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002861 break;
2862
2863 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002864 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002865 break;
2866 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002867 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002868 break;
2869 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002870 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002871 break;
2872 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002873 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002874 break;
2875 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002876 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002877 break;
2878 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002879 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002880 break;
2881
2882 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002883 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002884 break;
2885 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002886 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002887 break;
2888
2889 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002890 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002891 break;
2892 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002893 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002894 break;
2895 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002896 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002897 break;
2898 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002899 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002900 break;
2901 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002902 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002903 break;
2904 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002905 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002906 break;
2907
2908 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002909 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002910 break;
2911 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002912 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002913 break;
2914 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002915 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002916 break;
2917 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002918 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002919 break;
2920 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002921 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002922 break;
2923 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002924 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002925 break;
2926
2927 case glslang::EOpIsNan:
2928 unaryOp = spv::OpIsNan;
2929 break;
2930 case glslang::EOpIsInf:
2931 unaryOp = spv::OpIsInf;
2932 break;
2933
Rex Xucbc426e2015-12-15 16:03:10 +08002934 case glslang::EOpFloatBitsToInt:
2935 case glslang::EOpFloatBitsToUint:
2936 case glslang::EOpIntBitsToFloat:
2937 case glslang::EOpUintBitsToFloat:
2938 unaryOp = spv::OpBitcast;
2939 break;
2940
John Kessenich140f3df2015-06-26 16:58:36 -06002941 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002942 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002943 break;
2944 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002945 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002946 break;
2947 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002948 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002949 break;
2950 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002951 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002952 break;
2953 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002954 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002955 break;
2956 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002957 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002958 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002959 case glslang::EOpPackSnorm4x8:
2960 libCall = spv::GLSLstd450PackSnorm4x8;
2961 break;
2962 case glslang::EOpUnpackSnorm4x8:
2963 libCall = spv::GLSLstd450UnpackSnorm4x8;
2964 break;
2965 case glslang::EOpPackUnorm4x8:
2966 libCall = spv::GLSLstd450PackUnorm4x8;
2967 break;
2968 case glslang::EOpUnpackUnorm4x8:
2969 libCall = spv::GLSLstd450UnpackUnorm4x8;
2970 break;
2971 case glslang::EOpPackDouble2x32:
2972 libCall = spv::GLSLstd450PackDouble2x32;
2973 break;
2974 case glslang::EOpUnpackDouble2x32:
2975 libCall = spv::GLSLstd450UnpackDouble2x32;
2976 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002977
2978 case glslang::EOpDPdx:
2979 unaryOp = spv::OpDPdx;
2980 break;
2981 case glslang::EOpDPdy:
2982 unaryOp = spv::OpDPdy;
2983 break;
2984 case glslang::EOpFwidth:
2985 unaryOp = spv::OpFwidth;
2986 break;
2987 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07002988 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002989 unaryOp = spv::OpDPdxFine;
2990 break;
2991 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07002992 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002993 unaryOp = spv::OpDPdyFine;
2994 break;
2995 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07002996 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002997 unaryOp = spv::OpFwidthFine;
2998 break;
2999 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003000 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003001 unaryOp = spv::OpDPdxCoarse;
3002 break;
3003 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003004 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003005 unaryOp = spv::OpDPdyCoarse;
3006 break;
3007 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003008 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003009 unaryOp = spv::OpFwidthCoarse;
3010 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003011 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003012 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003013 libCall = spv::GLSLstd450InterpolateAtCentroid;
3014 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003015 case glslang::EOpAny:
3016 unaryOp = spv::OpAny;
3017 break;
3018 case glslang::EOpAll:
3019 unaryOp = spv::OpAll;
3020 break;
3021
3022 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003023 if (isFloat)
3024 libCall = spv::GLSLstd450FAbs;
3025 else
3026 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003027 break;
3028 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003029 if (isFloat)
3030 libCall = spv::GLSLstd450FSign;
3031 else
3032 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003033 break;
3034
John Kessenichfc51d282015-08-19 13:34:18 -06003035 case glslang::EOpAtomicCounterIncrement:
3036 case glslang::EOpAtomicCounterDecrement:
3037 case glslang::EOpAtomicCounter:
3038 {
3039 // Handle all of the atomics in one place, in createAtomicOperation()
3040 std::vector<spv::Id> operands;
3041 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003042 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003043 }
3044
John Kessenichfc51d282015-08-19 13:34:18 -06003045 case glslang::EOpBitFieldReverse:
3046 unaryOp = spv::OpBitReverse;
3047 break;
3048 case glslang::EOpBitCount:
3049 unaryOp = spv::OpBitCount;
3050 break;
3051 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003052 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003053 break;
3054 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003055 if (isUnsigned)
3056 libCall = spv::GLSLstd450FindUMsb;
3057 else
3058 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003059 break;
3060
John Kessenich140f3df2015-06-26 16:58:36 -06003061 default:
3062 return 0;
3063 }
3064
3065 spv::Id id;
3066 if (libCall >= 0) {
3067 std::vector<spv::Id> args;
3068 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003069 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003070 } else
3071 id = builder.createUnaryOp(unaryOp, typeId, operand);
3072
John Kessenich32cfd492016-02-02 12:37:46 -07003073 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003074}
3075
John Kessenich7a53f762016-01-20 11:19:27 -07003076// Create a unary operation on a matrix
3077spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3078{
3079 // Handle unary operations vector by vector.
3080 // The result type is the same type as the original type.
3081 // The algorithm is to:
3082 // - break the matrix into vectors
3083 // - apply the operation to each vector
3084 // - make a matrix out the vector results
3085
3086 // get the types sorted out
3087 int numCols = builder.getNumColumns(operand);
3088 int numRows = builder.getNumRows(operand);
3089 spv::Id scalarType = builder.getScalarTypeId(typeId);
3090 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3091 std::vector<spv::Id> results;
3092
3093 // do each vector op
3094 for (int c = 0; c < numCols; ++c) {
3095 std::vector<unsigned int> indexes;
3096 indexes.push_back(c);
3097 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3098 results.push_back(builder.createUnaryOp(op, vecType, vec));
3099 builder.setPrecision(results.back(), precision);
3100 }
3101
3102 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003103 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003104}
3105
John Kessenich140f3df2015-06-26 16:58:36 -06003106spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3107{
3108 spv::Op convOp = spv::OpNop;
3109 spv::Id zero = 0;
3110 spv::Id one = 0;
3111
3112 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3113
3114 switch (op) {
3115 case glslang::EOpConvIntToBool:
3116 case glslang::EOpConvUintToBool:
3117 zero = builder.makeUintConstant(0);
3118 zero = makeSmearedConstant(zero, vectorSize);
3119 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3120
3121 case glslang::EOpConvFloatToBool:
3122 zero = builder.makeFloatConstant(0.0F);
3123 zero = makeSmearedConstant(zero, vectorSize);
3124 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3125
3126 case glslang::EOpConvDoubleToBool:
3127 zero = builder.makeDoubleConstant(0.0);
3128 zero = makeSmearedConstant(zero, vectorSize);
3129 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3130
3131 case glslang::EOpConvBoolToFloat:
3132 convOp = spv::OpSelect;
3133 zero = builder.makeFloatConstant(0.0);
3134 one = builder.makeFloatConstant(1.0);
3135 break;
3136 case glslang::EOpConvBoolToDouble:
3137 convOp = spv::OpSelect;
3138 zero = builder.makeDoubleConstant(0.0);
3139 one = builder.makeDoubleConstant(1.0);
3140 break;
3141 case glslang::EOpConvBoolToInt:
3142 zero = builder.makeIntConstant(0);
3143 one = builder.makeIntConstant(1);
3144 convOp = spv::OpSelect;
3145 break;
3146 case glslang::EOpConvBoolToUint:
3147 zero = builder.makeUintConstant(0);
3148 one = builder.makeUintConstant(1);
3149 convOp = spv::OpSelect;
3150 break;
3151
3152 case glslang::EOpConvIntToFloat:
3153 case glslang::EOpConvIntToDouble:
3154 convOp = spv::OpConvertSToF;
3155 break;
3156
3157 case glslang::EOpConvUintToFloat:
3158 case glslang::EOpConvUintToDouble:
3159 convOp = spv::OpConvertUToF;
3160 break;
3161
3162 case glslang::EOpConvDoubleToFloat:
3163 case glslang::EOpConvFloatToDouble:
3164 convOp = spv::OpFConvert;
3165 break;
3166
3167 case glslang::EOpConvFloatToInt:
3168 case glslang::EOpConvDoubleToInt:
3169 convOp = spv::OpConvertFToS;
3170 break;
3171
3172 case glslang::EOpConvUintToInt:
3173 case glslang::EOpConvIntToUint:
3174 convOp = spv::OpBitcast;
3175 break;
3176
3177 case glslang::EOpConvFloatToUint:
3178 case glslang::EOpConvDoubleToUint:
3179 convOp = spv::OpConvertFToU;
3180 break;
3181 default:
3182 break;
3183 }
3184
3185 spv::Id result = 0;
3186 if (convOp == spv::OpNop)
3187 return result;
3188
3189 if (convOp == spv::OpSelect) {
3190 zero = makeSmearedConstant(zero, vectorSize);
3191 one = makeSmearedConstant(one, vectorSize);
3192 result = builder.createTriOp(convOp, destType, operand, one, zero);
3193 } else
3194 result = builder.createUnaryOp(convOp, destType, operand);
3195
John Kessenich32cfd492016-02-02 12:37:46 -07003196 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003197}
3198
3199spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3200{
3201 if (vectorSize == 0)
3202 return constant;
3203
3204 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3205 std::vector<spv::Id> components;
3206 for (int c = 0; c < vectorSize; ++c)
3207 components.push_back(constant);
3208 return builder.makeCompositeConstant(vectorTypeId, components);
3209}
3210
John Kessenich426394d2015-07-23 10:22:48 -06003211// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003212spv::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 -06003213{
3214 spv::Op opCode = spv::OpNop;
3215
3216 switch (op) {
3217 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003218 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003219 opCode = spv::OpAtomicIAdd;
3220 break;
3221 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003222 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003223 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003224 break;
3225 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003226 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003227 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003228 break;
3229 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003230 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003231 opCode = spv::OpAtomicAnd;
3232 break;
3233 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003234 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003235 opCode = spv::OpAtomicOr;
3236 break;
3237 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003238 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003239 opCode = spv::OpAtomicXor;
3240 break;
3241 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003242 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003243 opCode = spv::OpAtomicExchange;
3244 break;
3245 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003246 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003247 opCode = spv::OpAtomicCompareExchange;
3248 break;
3249 case glslang::EOpAtomicCounterIncrement:
3250 opCode = spv::OpAtomicIIncrement;
3251 break;
3252 case glslang::EOpAtomicCounterDecrement:
3253 opCode = spv::OpAtomicIDecrement;
3254 break;
3255 case glslang::EOpAtomicCounter:
3256 opCode = spv::OpAtomicLoad;
3257 break;
3258 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003259 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003260 break;
3261 }
3262
3263 // Sort out the operands
3264 // - mapping from glslang -> SPV
3265 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003266 // - compare-exchange swaps the value and comparator
3267 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003268 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3269 auto opIt = operands.begin(); // walk the glslang operands
3270 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003271 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3272 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3273 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003274 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3275 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003276 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003277 spvAtomicOperands.push_back(*(opIt + 1));
3278 spvAtomicOperands.push_back(*opIt);
3279 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003280 }
John Kessenich426394d2015-07-23 10:22:48 -06003281
John Kessenich3e60a6f2015-09-14 22:45:16 -06003282 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003283 for (; opIt != operands.end(); ++opIt)
3284 spvAtomicOperands.push_back(*opIt);
3285
3286 return builder.createOp(opCode, typeId, spvAtomicOperands);
3287}
3288
John Kessenich5e4b1242015-08-06 22:53:06 -06003289spv::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 -06003290{
John Kessenich5e4b1242015-08-06 22:53:06 -06003291 bool isUnsigned = typeProxy == glslang::EbtUint;
3292 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3293
John Kessenich140f3df2015-06-26 16:58:36 -06003294 spv::Op opCode = spv::OpNop;
3295 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003296 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003297 spv::Id typeId0 = 0;
3298 if (consumedOperands > 0)
3299 typeId0 = builder.getTypeId(operands[0]);
3300 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003301
3302 switch (op) {
3303 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003304 if (isFloat)
3305 libCall = spv::GLSLstd450FMin;
3306 else if (isUnsigned)
3307 libCall = spv::GLSLstd450UMin;
3308 else
3309 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003310 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003311 break;
3312 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003313 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003314 break;
3315 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003316 if (isFloat)
3317 libCall = spv::GLSLstd450FMax;
3318 else if (isUnsigned)
3319 libCall = spv::GLSLstd450UMax;
3320 else
3321 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003322 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003323 break;
3324 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003325 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003326 break;
3327 case glslang::EOpDot:
3328 opCode = spv::OpDot;
3329 break;
3330 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003331 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003332 break;
3333
3334 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003335 if (isFloat)
3336 libCall = spv::GLSLstd450FClamp;
3337 else if (isUnsigned)
3338 libCall = spv::GLSLstd450UClamp;
3339 else
3340 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003341 builder.promoteScalar(precision, operands.front(), operands[1]);
3342 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003343 break;
3344 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003345 if (isFloat)
3346 libCall = spv::GLSLstd450FMix;
John Kessenich6c292d32016-02-15 20:58:50 -07003347 else {
3348 opCode = spv::OpSelect;
3349 spv::MissingFunctionality("translating integer mix to OpSelect");
3350 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003351 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003352 break;
3353 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003354 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003355 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003356 break;
3357 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003358 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003359 builder.promoteScalar(precision, operands[0], operands[2]);
3360 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003361 break;
3362
3363 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003364 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003365 break;
3366 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003367 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003368 break;
3369 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003370 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003371 break;
3372 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003373 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003374 break;
3375 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003376 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003377 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003378 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003379 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003380 libCall = spv::GLSLstd450InterpolateAtSample;
3381 break;
3382 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003383 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003384 libCall = spv::GLSLstd450InterpolateAtOffset;
3385 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003386 case glslang::EOpAddCarry:
3387 opCode = spv::OpIAddCarry;
3388 typeId = builder.makeStructResultType(typeId0, typeId0);
3389 consumedOperands = 2;
3390 break;
3391 case glslang::EOpSubBorrow:
3392 opCode = spv::OpISubBorrow;
3393 typeId = builder.makeStructResultType(typeId0, typeId0);
3394 consumedOperands = 2;
3395 break;
3396 case glslang::EOpUMulExtended:
3397 opCode = spv::OpUMulExtended;
3398 typeId = builder.makeStructResultType(typeId0, typeId0);
3399 consumedOperands = 2;
3400 break;
3401 case glslang::EOpIMulExtended:
3402 opCode = spv::OpSMulExtended;
3403 typeId = builder.makeStructResultType(typeId0, typeId0);
3404 consumedOperands = 2;
3405 break;
3406 case glslang::EOpBitfieldExtract:
3407 if (isUnsigned)
3408 opCode = spv::OpBitFieldUExtract;
3409 else
3410 opCode = spv::OpBitFieldSExtract;
3411 break;
3412 case glslang::EOpBitfieldInsert:
3413 opCode = spv::OpBitFieldInsert;
3414 break;
3415
3416 case glslang::EOpFma:
3417 libCall = spv::GLSLstd450Fma;
3418 break;
3419 case glslang::EOpFrexp:
3420 libCall = spv::GLSLstd450FrexpStruct;
3421 if (builder.getNumComponents(operands[0]) == 1)
3422 frexpIntType = builder.makeIntegerType(32, true);
3423 else
3424 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3425 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3426 consumedOperands = 1;
3427 break;
3428 case glslang::EOpLdexp:
3429 libCall = spv::GLSLstd450Ldexp;
3430 break;
3431
John Kessenich140f3df2015-06-26 16:58:36 -06003432 default:
3433 return 0;
3434 }
3435
3436 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003437 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003438 // Use an extended instruction from the standard library.
3439 // Construct the call arguments, without modifying the original operands vector.
3440 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3441 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003442 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003443 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003444 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003445 case 0:
3446 // should all be handled by visitAggregate and createNoArgOperation
3447 assert(0);
3448 return 0;
3449 case 1:
3450 // should all be handled by createUnaryOperation
3451 assert(0);
3452 return 0;
3453 case 2:
3454 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3455 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003456 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003457 // anything 3 or over doesn't have l-value operands, so all should be consumed
3458 assert(consumedOperands == operands.size());
3459 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003460 break;
3461 }
3462 }
3463
John Kessenich55e7d112015-11-15 21:33:39 -07003464 // Decode the return types that were structures
3465 switch (op) {
3466 case glslang::EOpAddCarry:
3467 case glslang::EOpSubBorrow:
3468 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3469 id = builder.createCompositeExtract(id, typeId0, 0);
3470 break;
3471 case glslang::EOpUMulExtended:
3472 case glslang::EOpIMulExtended:
3473 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3474 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3475 break;
3476 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003477 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003478 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3479 id = builder.createCompositeExtract(id, typeId0, 0);
3480 break;
3481 default:
3482 break;
3483 }
3484
John Kessenich32cfd492016-02-02 12:37:46 -07003485 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003486}
3487
3488// Intrinsics with no arguments, no return value, and no precision.
3489spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3490{
3491 // TODO: get the barrier operands correct
3492
3493 switch (op) {
3494 case glslang::EOpEmitVertex:
3495 builder.createNoResultOp(spv::OpEmitVertex);
3496 return 0;
3497 case glslang::EOpEndPrimitive:
3498 builder.createNoResultOp(spv::OpEndPrimitive);
3499 return 0;
3500 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003501 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3502 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003503 return 0;
3504 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003505 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003506 return 0;
3507 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003508 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003509 return 0;
3510 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003511 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003512 return 0;
3513 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003514 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003515 return 0;
3516 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003517 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003518 return 0;
3519 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003520 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003521 return 0;
3522 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003523 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003524 return 0;
3525 }
3526}
3527
3528spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3529{
John Kessenich2f273362015-07-18 22:34:27 -06003530 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003531 spv::Id id;
3532 if (symbolValues.end() != iter) {
3533 id = iter->second;
3534 return id;
3535 }
3536
3537 // it was not found, create it
3538 id = createSpvVariable(symbol);
3539 symbolValues[symbol->getId()] = id;
3540
3541 if (! symbol->getType().isStruct()) {
3542 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003543 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003544 if (symbol->getType().getQualifier().hasSpecConstantId())
3545 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003546 if (symbol->getQualifier().hasLocation())
3547 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3548 if (symbol->getQualifier().hasIndex())
3549 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3550 if (symbol->getQualifier().hasComponent())
3551 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3552 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003553 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003554 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003555 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003556 if (symbol->getQualifier().hasXfbBuffer())
3557 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3558 if (symbol->getQualifier().hasXfbOffset())
3559 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3560 }
3561 }
3562
John Kesseniche0b6cad2015-12-24 10:30:13 -07003563 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenich92187592016-02-01 13:45:25 -07003564 if (symbol->getQualifier().hasStream()) {
3565 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003566 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003567 }
John Kessenich140f3df2015-06-26 16:58:36 -06003568 if (symbol->getQualifier().hasSet())
3569 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003570 else if (IsDescriptorResource(symbol->getType())) {
3571 // default to 0
3572 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3573 }
John Kessenich140f3df2015-06-26 16:58:36 -06003574 if (symbol->getQualifier().hasBinding())
3575 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003576 if (symbol->getQualifier().hasAttachment())
3577 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003578 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003579 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003580 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003581 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003582 if (symbol->getQualifier().hasXfbBuffer())
3583 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3584 }
3585
3586 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003587 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003588 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003589 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003590
John Kessenich140f3df2015-06-26 16:58:36 -06003591 return id;
3592}
3593
John Kessenich55e7d112015-11-15 21:33:39 -07003594// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003595void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3596{
3597 if (dec != spv::BadValue)
3598 builder.addDecoration(id, dec);
3599}
3600
John Kessenich55e7d112015-11-15 21:33:39 -07003601// If 'dec' is valid, add a one-operand decoration to an object
3602void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3603{
3604 if (dec != spv::BadValue)
3605 builder.addDecoration(id, dec, value);
3606}
3607
3608// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003609void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3610{
3611 if (dec != spv::BadValue)
3612 builder.addMemberDecoration(id, (unsigned)member, dec);
3613}
3614
John Kessenich92187592016-02-01 13:45:25 -07003615// If 'dec' is valid, add a one-operand decoration to a struct member
3616void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3617{
3618 if (dec != spv::BadValue)
3619 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3620}
3621
John Kessenich55e7d112015-11-15 21:33:39 -07003622// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003623// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003624//
3625// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3626//
3627// Recursively walk the nodes. The nodes form a tree whose leaves are
3628// regular constants, which themselves are trees that createSpvConstant()
3629// recursively walks. So, this function walks the "top" of the tree:
3630// - emit specialization constant-building instructions for specConstant
3631// - when running into a non-spec-constant, switch to createSpvConstant()
3632spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3633{
3634 assert(node.getQualifier().storage == glslang::EvqConst);
3635
John Kessenich6c292d32016-02-15 20:58:50 -07003636 if (! node.getQualifier().specConstant) {
3637 // hand off to the non-spec-constant path
3638 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3639 int nextConst = 0;
3640 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3641 nextConst, false);
3642 }
3643
3644 // We now know we have a specialization constant to build
3645
3646 if (node.getAsSymbolNode() && node.getQualifier().hasSpecConstantId()) {
3647 // this is a direct literal assigned to a layout(constant_id=) declaration
3648 int nextConst = 0;
3649 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3650 nextConst, true);
3651 } else {
3652 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3653 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3654 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3655 std::vector<spv::Id> dimConstId;
3656 for (int dim = 0; dim < 3; ++dim) {
3657 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3658 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3659 if (specConst)
3660 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3661 }
3662 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3663 } else {
3664 spv::MissingFunctionality("specialization-constant expression trees");
3665 return spv::NoResult;
3666 }
3667 }
John Kessenich55e7d112015-11-15 21:33:39 -07003668}
3669
John Kessenich140f3df2015-06-26 16:58:36 -06003670// Use 'consts' as the flattened glslang source of scalar constants to recursively
3671// build the aggregate SPIR-V constant.
3672//
3673// If there are not enough elements present in 'consts', 0 will be substituted;
3674// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3675//
John Kessenich55e7d112015-11-15 21:33:39 -07003676spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003677{
3678 // vector of constants for SPIR-V
3679 std::vector<spv::Id> spvConsts;
3680
3681 // Type is used for struct and array constants
3682 spv::Id typeId = convertGlslangToSpvType(glslangType);
3683
3684 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003685 glslang::TType elementType(glslangType, 0);
3686 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003687 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003688 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003689 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003690 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003691 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003692 } else if (glslangType.getStruct()) {
3693 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3694 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003695 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003696 } else if (glslangType.isVector()) {
3697 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3698 bool zero = nextConst >= consts.size();
3699 switch (glslangType.getBasicType()) {
3700 case glslang::EbtInt:
3701 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3702 break;
3703 case glslang::EbtUint:
3704 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3705 break;
3706 case glslang::EbtFloat:
3707 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3708 break;
3709 case glslang::EbtDouble:
3710 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3711 break;
3712 case glslang::EbtBool:
3713 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3714 break;
3715 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003716 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003717 break;
3718 }
3719 ++nextConst;
3720 }
3721 } else {
3722 // we have a non-aggregate (scalar) constant
3723 bool zero = nextConst >= consts.size();
3724 spv::Id scalar = 0;
3725 switch (glslangType.getBasicType()) {
3726 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003727 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003728 break;
3729 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003730 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003731 break;
3732 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003733 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003734 break;
3735 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003736 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003737 break;
3738 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003739 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003740 break;
3741 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003742 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003743 break;
3744 }
3745 ++nextConst;
3746 return scalar;
3747 }
3748
3749 return builder.makeCompositeConstant(typeId, spvConsts);
3750}
3751
John Kessenich7c1aa102015-10-15 13:29:11 -06003752// Return true if the node is a constant or symbol whose reading has no
3753// non-trivial observable cost or effect.
3754bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3755{
3756 // don't know what this is
3757 if (node == nullptr)
3758 return false;
3759
3760 // a constant is safe
3761 if (node->getAsConstantUnion() != nullptr)
3762 return true;
3763
3764 // not a symbol means non-trivial
3765 if (node->getAsSymbolNode() == nullptr)
3766 return false;
3767
3768 // a symbol, depends on what's being read
3769 switch (node->getType().getQualifier().storage) {
3770 case glslang::EvqTemporary:
3771 case glslang::EvqGlobal:
3772 case glslang::EvqIn:
3773 case glslang::EvqInOut:
3774 case glslang::EvqConst:
3775 case glslang::EvqConstReadOnly:
3776 case glslang::EvqUniform:
3777 return true;
3778 default:
3779 return false;
3780 }
3781}
3782
3783// A node is trivial if it is a single operation with no side effects.
3784// Error on the side of saying non-trivial.
3785// Return true if trivial.
3786bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3787{
3788 if (node == nullptr)
3789 return false;
3790
3791 // symbols and constants are trivial
3792 if (isTrivialLeaf(node))
3793 return true;
3794
3795 // otherwise, it needs to be a simple operation or one or two leaf nodes
3796
3797 // not a simple operation
3798 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3799 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3800 if (binaryNode == nullptr && unaryNode == nullptr)
3801 return false;
3802
3803 // not on leaf nodes
3804 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3805 return false;
3806
3807 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3808 return false;
3809 }
3810
3811 switch (node->getAsOperator()->getOp()) {
3812 case glslang::EOpLogicalNot:
3813 case glslang::EOpConvIntToBool:
3814 case glslang::EOpConvUintToBool:
3815 case glslang::EOpConvFloatToBool:
3816 case glslang::EOpConvDoubleToBool:
3817 case glslang::EOpEqual:
3818 case glslang::EOpNotEqual:
3819 case glslang::EOpLessThan:
3820 case glslang::EOpGreaterThan:
3821 case glslang::EOpLessThanEqual:
3822 case glslang::EOpGreaterThanEqual:
3823 case glslang::EOpIndexDirect:
3824 case glslang::EOpIndexDirectStruct:
3825 case glslang::EOpLogicalXor:
3826 case glslang::EOpAny:
3827 case glslang::EOpAll:
3828 return true;
3829 default:
3830 return false;
3831 }
3832}
3833
3834// Emit short-circuiting code, where 'right' is never evaluated unless
3835// the left side is true (for &&) or false (for ||).
3836spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3837{
3838 spv::Id boolTypeId = builder.makeBoolType();
3839
3840 // emit left operand
3841 builder.clearAccessChain();
3842 left.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003843 spv::Id leftId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003844
3845 // Operands to accumulate OpPhi operands
3846 std::vector<spv::Id> phiOperands;
3847 // accumulate left operand's phi information
3848 phiOperands.push_back(leftId);
3849 phiOperands.push_back(builder.getBuildPoint()->getId());
3850
3851 // Make the two kinds of operation symmetric with a "!"
3852 // || => emit "if (! left) result = right"
3853 // && => emit "if ( left) result = right"
3854 //
3855 // TODO: this runtime "not" for || could be avoided by adding functionality
3856 // to 'builder' to have an "else" without an "then"
3857 if (op == glslang::EOpLogicalOr)
3858 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3859
3860 // make an "if" based on the left value
3861 spv::Builder::If ifBuilder(leftId, builder);
3862
3863 // emit right operand as the "then" part of the "if"
3864 builder.clearAccessChain();
3865 right.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003866 spv::Id rightId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003867
3868 // accumulate left operand's phi information
3869 phiOperands.push_back(rightId);
3870 phiOperands.push_back(builder.getBuildPoint()->getId());
3871
3872 // finish the "if"
3873 ifBuilder.makeEndIf();
3874
3875 // phi together the two results
3876 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3877}
3878
John Kessenich140f3df2015-06-26 16:58:36 -06003879}; // end anonymous namespace
3880
3881namespace glslang {
3882
John Kessenich68d78fd2015-07-12 19:28:10 -06003883void GetSpirvVersion(std::string& version)
3884{
John Kessenich9e55f632015-07-15 10:03:39 -06003885 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003886 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003887 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003888 version = buf;
3889}
3890
John Kessenich140f3df2015-06-26 16:58:36 -06003891// Write SPIR-V out to a binary file
3892void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3893{
3894 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003895 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003896 for (int i = 0; i < (int)spirv.size(); ++i) {
3897 unsigned int word = spirv[i];
3898 out.write((const char*)&word, 4);
3899 }
3900 out.close();
3901}
3902
3903//
3904// Set up the glslang traversal
3905//
3906void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3907{
3908 TIntermNode* root = intermediate.getTreeRoot();
3909
3910 if (root == 0)
3911 return;
3912
3913 glslang::GetThreadPoolAllocator().push();
3914
3915 TGlslangToSpvTraverser it(&intermediate);
3916
3917 root->traverse(&it);
3918
3919 it.dumpSpv(spirv);
3920
3921 glslang::GetThreadPoolAllocator().pop();
3922}
3923
3924}; // end namespace glslang