blob: 20c58f740aa71af603d2cb1b6a68019082c3603c [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;
538}
539
540bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
541{
John Kessenich7b9fa252016-01-21 18:56:57 -0700542 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700543 // - struct members can inherit from a struct declaration
544 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
545 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700546 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700547}
548
John Kessenich140f3df2015-06-26 16:58:36 -0600549//
550// Implement the TGlslangToSpvTraverser class.
551//
552
553TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
554 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700555 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600556 inMain(false), mainTerminated(false), linkageOnly(false),
557 glslangIntermediate(glslangIntermediate)
558{
559 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
560
561 builder.clearAccessChain();
562 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
563 stdBuiltins = builder.import("GLSL.std.450");
564 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
565 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700566 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600567
568 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600569 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
570 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600571 builder.addSourceExtension(it->c_str());
572
573 // Add the top-level modes for this shader.
574
John Kessenich92187592016-02-01 13:45:25 -0700575 if (glslangIntermediate->getXfbMode()) {
576 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600577 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700578 }
John Kessenich140f3df2015-06-26 16:58:36 -0600579
580 unsigned int mode;
581 switch (glslangIntermediate->getStage()) {
582 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600583 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600584 break;
585
586 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600587 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600588 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
589 break;
590
591 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600592 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600593 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700594 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
595 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
596 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600597 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600598 }
599 if (mode != spv::BadValue)
600 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
601
John Kesseniche6903322015-10-13 16:29:02 -0600602 switch (glslangIntermediate->getVertexSpacing()) {
603 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
604 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
605 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
606 default: mode = spv::BadValue; break;
607 }
608 if (mode != spv::BadValue)
609 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
610
611 switch (glslangIntermediate->getVertexOrder()) {
612 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
613 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
614 default: mode = spv::BadValue; break;
615 }
616 if (mode != spv::BadValue)
617 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
618
619 if (glslangIntermediate->getPointMode())
620 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600621 break;
622
623 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600624 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600625 switch (glslangIntermediate->getInputPrimitive()) {
626 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
627 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
628 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700629 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600630 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
631 default: mode = spv::BadValue; break;
632 }
633 if (mode != spv::BadValue)
634 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600635
John Kessenich140f3df2015-06-26 16:58:36 -0600636 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
637
638 switch (glslangIntermediate->getOutputPrimitive()) {
639 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
640 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
641 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
642 default: mode = spv::BadValue; break;
643 }
644 if (mode != spv::BadValue)
645 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
646 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
647 break;
648
649 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600650 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600651 if (glslangIntermediate->getPixelCenterInteger())
652 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600653
John Kessenich140f3df2015-06-26 16:58:36 -0600654 if (glslangIntermediate->getOriginUpperLeft())
655 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600656 else
657 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600658
659 if (glslangIntermediate->getEarlyFragmentTests())
660 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
661
662 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600663 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
664 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
665 default: mode = spv::BadValue; break;
666 }
667 if (mode != spv::BadValue)
668 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
669
670 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
671 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600672 break;
673
674 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600675 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600676 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
677 glslangIntermediate->getLocalSize(1),
678 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600679 break;
680
681 default:
682 break;
683 }
684
685}
686
John Kessenich7ba63412015-12-20 17:37:07 -0700687// Finish everything and dump
688void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
689{
690 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100691 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
692 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700693
694 builder.dump(out);
695}
696
John Kessenich140f3df2015-06-26 16:58:36 -0600697TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
698{
699 if (! mainTerminated) {
700 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
701 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600702 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600703 }
704}
705
706//
707// Implement the traversal functions.
708//
709// Return true from interior nodes to have the external traversal
710// continue on to children. Return false if children were
711// already processed.
712//
713
714//
715// Symbols can turn into
716// - uniform/input reads
717// - output writes
718// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
719// - something simple that degenerates into the last bullet
720//
721void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
722{
723 // getSymbolId() will set up all the IO decorations on the first call.
724 // Formal function parameters were mapped during makeFunctions().
725 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700726
727 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
728 if (builder.isPointer(id)) {
729 spv::StorageClass sc = builder.getStorageClass(id);
730 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
731 iOSet.insert(id);
732 }
733
734 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700735 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600736 // Prepare to generate code for the access
737
738 // L-value chains will be computed left to right. We're on the symbol now,
739 // which is the left-most part of the access chain, so now is "clear" time,
740 // followed by setting the base.
741 builder.clearAccessChain();
742
743 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700744 // except for
745 // A) "const in" arguments to a function, which are an intermediate object.
746 // See comments in handleUserFunctionCall().
747 // B) Specialization constants (normal constant don't even come in as a variable),
748 // These are also pure R-values.
749 glslang::TQualifier qualifier = symbol->getQualifier();
750 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
751 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600752 builder.setAccessChainRValue(id);
753 else
754 builder.setAccessChainLValue(id);
755 }
756}
757
758bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
759{
760 // First, handle special cases
761 switch (node->getOp()) {
762 case glslang::EOpAssign:
763 case glslang::EOpAddAssign:
764 case glslang::EOpSubAssign:
765 case glslang::EOpMulAssign:
766 case glslang::EOpVectorTimesMatrixAssign:
767 case glslang::EOpVectorTimesScalarAssign:
768 case glslang::EOpMatrixTimesScalarAssign:
769 case glslang::EOpMatrixTimesMatrixAssign:
770 case glslang::EOpDivAssign:
771 case glslang::EOpModAssign:
772 case glslang::EOpAndAssign:
773 case glslang::EOpInclusiveOrAssign:
774 case glslang::EOpExclusiveOrAssign:
775 case glslang::EOpLeftShiftAssign:
776 case glslang::EOpRightShiftAssign:
777 // A bin-op assign "a += b" means the same thing as "a = a + b"
778 // where a is evaluated before b. For a simple assignment, GLSL
779 // says to evaluate the left before the right. So, always, left
780 // node then right node.
781 {
782 // get the left l-value, save it away
783 builder.clearAccessChain();
784 node->getLeft()->traverse(this);
785 spv::Builder::AccessChain lValue = builder.getAccessChain();
786
787 // evaluate the right
788 builder.clearAccessChain();
789 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700790 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600791
792 if (node->getOp() != glslang::EOpAssign) {
793 // the left is also an r-value
794 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700795 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600796
797 // do the operation
798 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
799 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
800 node->getType().getBasicType());
801
802 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700803 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600804 }
805
806 // store the result
807 builder.setAccessChain(lValue);
808 builder.accessChainStore(rValue);
809
810 // assignments are expressions having an rValue after they are evaluated...
811 builder.clearAccessChain();
812 builder.setAccessChainRValue(rValue);
813 }
814 return false;
815 case glslang::EOpIndexDirect:
816 case glslang::EOpIndexDirectStruct:
817 {
818 // Get the left part of the access chain.
819 node->getLeft()->traverse(this);
820
821 // Add the next element in the chain
822
John Kessenich55e7d112015-11-15 21:33:39 -0700823 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600824 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
825 // This may be, e.g., an anonymous block-member selection, which generally need
826 // index remapping due to hidden members in anonymous blocks.
827 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700828 assert(remapper.size() > 0);
829 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600830 }
831
832 if (! node->getLeft()->getType().isArray() &&
833 node->getLeft()->getType().isVector() &&
834 node->getOp() == glslang::EOpIndexDirect) {
835 // This is essentially a hard-coded vector swizzle of size 1,
836 // so short circuit the access-chain stuff with a swizzle.
837 std::vector<unsigned> swizzle;
838 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600839 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600840 } else {
841 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600842 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600843 }
844 }
845 return false;
846 case glslang::EOpIndexIndirect:
847 {
848 // Structure or array or vector indirection.
849 // Will use native SPIR-V access-chain for struct and array indirection;
850 // matrices are arrays of vectors, so will also work for a matrix.
851 // Will use the access chain's 'component' for variable index into a vector.
852
853 // This adapter is building access chains left to right.
854 // Set up the access chain to the left.
855 node->getLeft()->traverse(this);
856
857 // save it so that computing the right side doesn't trash it
858 spv::Builder::AccessChain partial = builder.getAccessChain();
859
860 // compute the next index in the chain
861 builder.clearAccessChain();
862 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700863 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600864
865 // restore the saved access chain
866 builder.setAccessChain(partial);
867
868 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600869 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600870 else
John Kessenichfa668da2015-09-13 14:46:30 -0600871 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600872 }
873 return false;
874 case glslang::EOpVectorSwizzle:
875 {
876 node->getLeft()->traverse(this);
877 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
878 std::vector<unsigned> swizzle;
879 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
880 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600881 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600882 }
883 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600884 case glslang::EOpLogicalOr:
885 case glslang::EOpLogicalAnd:
886 {
887
888 // These may require short circuiting, but can sometimes be done as straight
889 // binary operations. The right operand must be short circuited if it has
890 // side effects, and should probably be if it is complex.
891 if (isTrivial(node->getRight()->getAsTyped()))
892 break; // handle below as a normal binary operation
893 // otherwise, we need to do dynamic short circuiting on the right operand
894 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
895 builder.clearAccessChain();
896 builder.setAccessChainRValue(result);
897 }
898 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600899 default:
900 break;
901 }
902
903 // Assume generic binary op...
904
John Kessenich32cfd492016-02-02 12:37:46 -0700905 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600906 builder.clearAccessChain();
907 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700908 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600909
John Kessenich32cfd492016-02-02 12:37:46 -0700910 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600911 builder.clearAccessChain();
912 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700913 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600914
John Kessenich32cfd492016-02-02 12:37:46 -0700915 // get result
916 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
917 convertGlslangToSpvType(node->getType()), left, right,
918 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600919
John Kessenich50e57562015-12-21 21:21:11 -0700920 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600921 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700922 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700923 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600924 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600925 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600926 return false;
927 }
John Kessenich140f3df2015-06-26 16:58:36 -0600928}
929
930bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
931{
John Kessenichfc51d282015-08-19 13:34:18 -0600932 spv::Id result = spv::NoResult;
933
934 // try texturing first
935 result = createImageTextureFunctionCall(node);
936 if (result != spv::NoResult) {
937 builder.clearAccessChain();
938 builder.setAccessChainRValue(result);
939
940 return false; // done with this node
941 }
942
943 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600944
945 if (node->getOp() == glslang::EOpArrayLength) {
946 // Quite special; won't want to evaluate the operand.
947
948 // Normal .length() would have been constant folded by the front-end.
949 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600950 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600951 assert(node->getOperand()->getType().isRuntimeSizedArray());
952 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
953 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600954 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
955 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600956
957 builder.clearAccessChain();
958 builder.setAccessChainRValue(length);
959
960 return false;
961 }
962
John Kessenichfc51d282015-08-19 13:34:18 -0600963 // Start by evaluating the operand
964
John Kessenich140f3df2015-06-26 16:58:36 -0600965 builder.clearAccessChain();
966 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800967
Rex Xufc618912015-09-09 16:42:49 +0800968 spv::Id operand = spv::NoResult;
969
970 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
971 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800972 node->getOp() == glslang::EOpAtomicCounter ||
973 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800974 operand = builder.accessChainGetLValue(); // Special case l-value operands
975 else
John Kessenich32cfd492016-02-02 12:37:46 -0700976 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600977
978 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
979
980 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600981 if (! result)
982 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600983
984 // if not, then possibly an operation
985 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700986 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600987
988 if (result) {
989 builder.clearAccessChain();
990 builder.setAccessChainRValue(result);
991
992 return false; // done with this node
993 }
994
995 // it must be a special case, check...
996 switch (node->getOp()) {
997 case glslang::EOpPostIncrement:
998 case glslang::EOpPostDecrement:
999 case glslang::EOpPreIncrement:
1000 case glslang::EOpPreDecrement:
1001 {
1002 // we need the integer value "1" or the floating point "1.0" to add/subtract
1003 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
1004 builder.makeFloatConstant(1.0F) :
1005 builder.makeIntConstant(1);
1006 glslang::TOperator op;
1007 if (node->getOp() == glslang::EOpPreIncrement ||
1008 node->getOp() == glslang::EOpPostIncrement)
1009 op = glslang::EOpAdd;
1010 else
1011 op = glslang::EOpSub;
1012
1013 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1014 convertGlslangToSpvType(node->getType()), operand, one,
1015 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001016 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001017
1018 // The result of operation is always stored, but conditionally the
1019 // consumed result. The consumed result is always an r-value.
1020 builder.accessChainStore(result);
1021 builder.clearAccessChain();
1022 if (node->getOp() == glslang::EOpPreIncrement ||
1023 node->getOp() == glslang::EOpPreDecrement)
1024 builder.setAccessChainRValue(result);
1025 else
1026 builder.setAccessChainRValue(operand);
1027 }
1028
1029 return false;
1030
1031 case glslang::EOpEmitStreamVertex:
1032 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1033 return false;
1034 case glslang::EOpEndStreamPrimitive:
1035 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1036 return false;
1037
1038 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001039 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001040 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001041 }
John Kessenich140f3df2015-06-26 16:58:36 -06001042}
1043
1044bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1045{
John Kessenichfc51d282015-08-19 13:34:18 -06001046 spv::Id result = spv::NoResult;
1047
1048 // try texturing
1049 result = createImageTextureFunctionCall(node);
1050 if (result != spv::NoResult) {
1051 builder.clearAccessChain();
1052 builder.setAccessChainRValue(result);
1053
1054 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001055 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001056 // "imageStore" is a special case, which has no result
1057 return false;
1058 }
John Kessenichfc51d282015-08-19 13:34:18 -06001059
John Kessenich140f3df2015-06-26 16:58:36 -06001060 glslang::TOperator binOp = glslang::EOpNull;
1061 bool reduceComparison = true;
1062 bool isMatrix = false;
1063 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001064 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001065
1066 assert(node->getOp());
1067
1068 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1069
1070 switch (node->getOp()) {
1071 case glslang::EOpSequence:
1072 {
1073 if (preVisit)
1074 ++sequenceDepth;
1075 else
1076 --sequenceDepth;
1077
1078 if (sequenceDepth == 1) {
1079 // If this is the parent node of all the functions, we want to see them
1080 // early, so all call points have actual SPIR-V functions to reference.
1081 // In all cases, still let the traverser visit the children for us.
1082 makeFunctions(node->getAsAggregate()->getSequence());
1083
1084 // Also, we want all globals initializers to go into the entry of main(), before
1085 // anything else gets there, so visit out of order, doing them all now.
1086 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1087
1088 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1089 // so do them manually.
1090 visitFunctions(node->getAsAggregate()->getSequence());
1091
1092 return false;
1093 }
1094
1095 return true;
1096 }
1097 case glslang::EOpLinkerObjects:
1098 {
1099 if (visit == glslang::EvPreVisit)
1100 linkageOnly = true;
1101 else
1102 linkageOnly = false;
1103
1104 return true;
1105 }
1106 case glslang::EOpComma:
1107 {
1108 // processing from left to right naturally leaves the right-most
1109 // lying around in the access chain
1110 glslang::TIntermSequence& glslangOperands = node->getSequence();
1111 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1112 glslangOperands[i]->traverse(this);
1113
1114 return false;
1115 }
1116 case glslang::EOpFunction:
1117 if (visit == glslang::EvPreVisit) {
1118 if (isShaderEntrypoint(node)) {
1119 inMain = true;
1120 builder.setBuildPoint(shaderEntry->getLastBlock());
1121 } else {
1122 handleFunctionEntry(node);
1123 }
1124 } else {
1125 if (inMain)
1126 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001127 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001128 inMain = false;
1129 }
1130
1131 return true;
1132 case glslang::EOpParameters:
1133 // Parameters will have been consumed by EOpFunction processing, but not
1134 // the body, so we still visited the function node's children, making this
1135 // child redundant.
1136 return false;
1137 case glslang::EOpFunctionCall:
1138 {
1139 if (node->isUserDefined())
1140 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001141 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1142 if (result) {
1143 builder.clearAccessChain();
1144 builder.setAccessChainRValue(result);
1145 } else
1146 spv::MissingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001147
1148 return false;
1149 }
1150 case glslang::EOpConstructMat2x2:
1151 case glslang::EOpConstructMat2x3:
1152 case glslang::EOpConstructMat2x4:
1153 case glslang::EOpConstructMat3x2:
1154 case glslang::EOpConstructMat3x3:
1155 case glslang::EOpConstructMat3x4:
1156 case glslang::EOpConstructMat4x2:
1157 case glslang::EOpConstructMat4x3:
1158 case glslang::EOpConstructMat4x4:
1159 case glslang::EOpConstructDMat2x2:
1160 case glslang::EOpConstructDMat2x3:
1161 case glslang::EOpConstructDMat2x4:
1162 case glslang::EOpConstructDMat3x2:
1163 case glslang::EOpConstructDMat3x3:
1164 case glslang::EOpConstructDMat3x4:
1165 case glslang::EOpConstructDMat4x2:
1166 case glslang::EOpConstructDMat4x3:
1167 case glslang::EOpConstructDMat4x4:
1168 isMatrix = true;
1169 // fall through
1170 case glslang::EOpConstructFloat:
1171 case glslang::EOpConstructVec2:
1172 case glslang::EOpConstructVec3:
1173 case glslang::EOpConstructVec4:
1174 case glslang::EOpConstructDouble:
1175 case glslang::EOpConstructDVec2:
1176 case glslang::EOpConstructDVec3:
1177 case glslang::EOpConstructDVec4:
1178 case glslang::EOpConstructBool:
1179 case glslang::EOpConstructBVec2:
1180 case glslang::EOpConstructBVec3:
1181 case glslang::EOpConstructBVec4:
1182 case glslang::EOpConstructInt:
1183 case glslang::EOpConstructIVec2:
1184 case glslang::EOpConstructIVec3:
1185 case glslang::EOpConstructIVec4:
1186 case glslang::EOpConstructUint:
1187 case glslang::EOpConstructUVec2:
1188 case glslang::EOpConstructUVec3:
1189 case glslang::EOpConstructUVec4:
1190 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001191 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001192 {
1193 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001194 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001195 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1196 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001197 if (node->getOp() == glslang::EOpConstructTextureSampler)
1198 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1199 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001200 std::vector<spv::Id> constituents;
1201 for (int c = 0; c < (int)arguments.size(); ++c)
1202 constituents.push_back(arguments[c]);
1203 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001204 } else if (isMatrix)
1205 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1206 else
1207 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001208
1209 builder.clearAccessChain();
1210 builder.setAccessChainRValue(constructed);
1211
1212 return false;
1213 }
1214
1215 // These six are component-wise compares with component-wise results.
1216 // Forward on to createBinaryOperation(), requesting a vector result.
1217 case glslang::EOpLessThan:
1218 case glslang::EOpGreaterThan:
1219 case glslang::EOpLessThanEqual:
1220 case glslang::EOpGreaterThanEqual:
1221 case glslang::EOpVectorEqual:
1222 case glslang::EOpVectorNotEqual:
1223 {
1224 // Map the operation to a binary
1225 binOp = node->getOp();
1226 reduceComparison = false;
1227 switch (node->getOp()) {
1228 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1229 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1230 default: binOp = node->getOp(); break;
1231 }
1232
1233 break;
1234 }
1235 case glslang::EOpMul:
1236 // compontent-wise matrix multiply
1237 binOp = glslang::EOpMul;
1238 break;
1239 case glslang::EOpOuterProduct:
1240 // two vectors multiplied to make a matrix
1241 binOp = glslang::EOpOuterProduct;
1242 break;
1243 case glslang::EOpDot:
1244 {
1245 // for scalar dot product, use multiply
1246 glslang::TIntermSequence& glslangOperands = node->getSequence();
1247 if (! glslangOperands[0]->getAsTyped()->isVector())
1248 binOp = glslang::EOpMul;
1249 break;
1250 }
1251 case glslang::EOpMod:
1252 // when an aggregate, this is the floating-point mod built-in function,
1253 // which can be emitted by the one in createBinaryOperation()
1254 binOp = glslang::EOpMod;
1255 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001256 case glslang::EOpEmitVertex:
1257 case glslang::EOpEndPrimitive:
1258 case glslang::EOpBarrier:
1259 case glslang::EOpMemoryBarrier:
1260 case glslang::EOpMemoryBarrierAtomicCounter:
1261 case glslang::EOpMemoryBarrierBuffer:
1262 case glslang::EOpMemoryBarrierImage:
1263 case glslang::EOpMemoryBarrierShared:
1264 case glslang::EOpGroupMemoryBarrier:
1265 noReturnValue = true;
1266 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1267 break;
1268
John Kessenich426394d2015-07-23 10:22:48 -06001269 case glslang::EOpAtomicAdd:
1270 case glslang::EOpAtomicMin:
1271 case glslang::EOpAtomicMax:
1272 case glslang::EOpAtomicAnd:
1273 case glslang::EOpAtomicOr:
1274 case glslang::EOpAtomicXor:
1275 case glslang::EOpAtomicExchange:
1276 case glslang::EOpAtomicCompSwap:
1277 atomic = true;
1278 break;
1279
John Kessenich140f3df2015-06-26 16:58:36 -06001280 default:
1281 break;
1282 }
1283
1284 //
1285 // See if it maps to a regular operation.
1286 //
John Kessenich140f3df2015-06-26 16:58:36 -06001287 if (binOp != glslang::EOpNull) {
1288 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1289 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1290 assert(left && right);
1291
1292 builder.clearAccessChain();
1293 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001294 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001295
1296 builder.clearAccessChain();
1297 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001298 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001299
1300 result = createBinaryOperation(binOp, precision,
1301 convertGlslangToSpvType(node->getType()), leftId, rightId,
1302 left->getType().getBasicType(), reduceComparison);
1303
1304 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001305 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001306 builder.clearAccessChain();
1307 builder.setAccessChainRValue(result);
1308
1309 return false;
1310 }
1311
John Kessenich426394d2015-07-23 10:22:48 -06001312 //
1313 // Create the list of operands.
1314 //
John Kessenich140f3df2015-06-26 16:58:36 -06001315 glslang::TIntermSequence& glslangOperands = node->getSequence();
1316 std::vector<spv::Id> operands;
1317 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1318 builder.clearAccessChain();
1319 glslangOperands[arg]->traverse(this);
1320
1321 // special case l-value operands; there are just a few
1322 bool lvalue = false;
1323 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001324 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001325 case glslang::EOpModf:
1326 if (arg == 1)
1327 lvalue = true;
1328 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001329 case glslang::EOpInterpolateAtSample:
1330 case glslang::EOpInterpolateAtOffset:
1331 if (arg == 0)
1332 lvalue = true;
1333 break;
Rex Xud4782c12015-09-06 16:30:11 +08001334 case glslang::EOpAtomicAdd:
1335 case glslang::EOpAtomicMin:
1336 case glslang::EOpAtomicMax:
1337 case glslang::EOpAtomicAnd:
1338 case glslang::EOpAtomicOr:
1339 case glslang::EOpAtomicXor:
1340 case glslang::EOpAtomicExchange:
1341 case glslang::EOpAtomicCompSwap:
1342 if (arg == 0)
1343 lvalue = true;
1344 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001345 case glslang::EOpAddCarry:
1346 case glslang::EOpSubBorrow:
1347 if (arg == 2)
1348 lvalue = true;
1349 break;
1350 case glslang::EOpUMulExtended:
1351 case glslang::EOpIMulExtended:
1352 if (arg >= 2)
1353 lvalue = true;
1354 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001355 default:
1356 break;
1357 }
1358 if (lvalue)
1359 operands.push_back(builder.accessChainGetLValue());
1360 else
John Kessenich32cfd492016-02-02 12:37:46 -07001361 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001362 }
John Kessenich426394d2015-07-23 10:22:48 -06001363
1364 if (atomic) {
1365 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001366 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001367 } else {
1368 // Pass through to generic operations.
1369 switch (glslangOperands.size()) {
1370 case 0:
1371 result = createNoArgOperation(node->getOp());
1372 break;
1373 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001374 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001375 break;
1376 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001377 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001378 break;
1379 }
John Kessenich140f3df2015-06-26 16:58:36 -06001380 }
1381
1382 if (noReturnValue)
1383 return false;
1384
1385 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001386 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001387 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001388 } else {
1389 builder.clearAccessChain();
1390 builder.setAccessChainRValue(result);
1391 return false;
1392 }
1393}
1394
1395bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1396{
1397 // This path handles both if-then-else and ?:
1398 // The if-then-else has a node type of void, while
1399 // ?: has a non-void node type
1400 spv::Id result = 0;
1401 if (node->getBasicType() != glslang::EbtVoid) {
1402 // don't handle this as just on-the-fly temporaries, because there will be two names
1403 // and better to leave SSA to later passes
1404 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1405 }
1406
1407 // emit the condition before doing anything with selection
1408 node->getCondition()->traverse(this);
1409
1410 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001411 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001412
1413 if (node->getTrueBlock()) {
1414 // emit the "then" statement
1415 node->getTrueBlock()->traverse(this);
1416 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001417 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001418 }
1419
1420 if (node->getFalseBlock()) {
1421 ifBuilder.makeBeginElse();
1422 // emit the "else" statement
1423 node->getFalseBlock()->traverse(this);
1424 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001425 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001426 }
1427
1428 ifBuilder.makeEndIf();
1429
1430 if (result) {
1431 // GLSL only has r-values as the result of a :?, but
1432 // if we have an l-value, that can be more efficient if it will
1433 // become the base of a complex r-value expression, because the
1434 // next layer copies r-values into memory to use the access-chain mechanism
1435 builder.clearAccessChain();
1436 builder.setAccessChainLValue(result);
1437 }
1438
1439 return false;
1440}
1441
1442bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1443{
1444 // emit and get the condition before doing anything with switch
1445 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001446 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001447
1448 // browse the children to sort out code segments
1449 int defaultSegment = -1;
1450 std::vector<TIntermNode*> codeSegments;
1451 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1452 std::vector<int> caseValues;
1453 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1454 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1455 TIntermNode* child = *c;
1456 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001457 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001458 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001459 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001460 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1461 } else
1462 codeSegments.push_back(child);
1463 }
1464
1465 // handle the case where the last code segment is missing, due to no code
1466 // statements between the last case and the end of the switch statement
1467 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1468 (int)codeSegments.size() == defaultSegment)
1469 codeSegments.push_back(nullptr);
1470
1471 // make the switch statement
1472 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001473 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001474
1475 // emit all the code in the segments
1476 breakForLoop.push(false);
1477 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1478 builder.nextSwitchSegment(segmentBlocks, s);
1479 if (codeSegments[s])
1480 codeSegments[s]->traverse(this);
1481 else
1482 builder.addSwitchBreak();
1483 }
1484 breakForLoop.pop();
1485
1486 builder.endSwitch(segmentBlocks);
1487
1488 return false;
1489}
1490
1491void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1492{
1493 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001494 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001495
1496 builder.clearAccessChain();
1497 builder.setAccessChainRValue(constant);
1498}
1499
1500bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1501{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001502 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001503 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001504 // Spec requires back edges to target header blocks, and every header block
1505 // must dominate its merge block. Make a header block first to ensure these
1506 // conditions are met. By definition, it will contain OpLoopMerge, followed
1507 // by a block-ending branch. But we don't want to put any other body/test
1508 // instructions in it, since the body/test may have arbitrary instructions,
1509 // including merges of its own.
1510 builder.setBuildPoint(&blocks.head);
1511 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001512 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001513 spv::Block& test = builder.makeNewBlock();
1514 builder.createBranch(&test);
1515
1516 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001517 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001518 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001519 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001520 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1521
1522 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001523 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001524 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001525 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001526 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001527 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001528
1529 builder.setBuildPoint(&blocks.continue_target);
1530 if (node->getTerminal())
1531 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001532 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001533 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001534 builder.createBranch(&blocks.body);
1535
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001536 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001537 builder.setBuildPoint(&blocks.body);
1538 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001539 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001540 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001541 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001542
1543 builder.setBuildPoint(&blocks.continue_target);
1544 if (node->getTerminal())
1545 node->getTerminal()->traverse(this);
1546 if (node->getTest()) {
1547 node->getTest()->traverse(this);
1548 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001549 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001550 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001551 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001552 // TODO: unless there was a break/return/discard instruction
1553 // somewhere in the body, this is an infinite loop, so we should
1554 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001555 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001556 }
John Kessenich140f3df2015-06-26 16:58:36 -06001557 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001558 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001559 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001560 return false;
1561}
1562
1563bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1564{
1565 if (node->getExpression())
1566 node->getExpression()->traverse(this);
1567
1568 switch (node->getFlowOp()) {
1569 case glslang::EOpKill:
1570 builder.makeDiscard();
1571 break;
1572 case glslang::EOpBreak:
1573 if (breakForLoop.top())
1574 builder.createLoopExit();
1575 else
1576 builder.addSwitchBreak();
1577 break;
1578 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001579 builder.createLoopContinue();
1580 break;
1581 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001582 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001583 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001584 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001585 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001586
1587 builder.clearAccessChain();
1588 break;
1589
1590 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001591 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001592 break;
1593 }
1594
1595 return false;
1596}
1597
1598spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1599{
1600 // First, steer off constants, which are not SPIR-V variables, but
1601 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001602 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001603 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001604 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001605 }
1606
1607 // Now, handle actual variables
1608 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1609 spv::Id spvType = convertGlslangToSpvType(node->getType());
1610
1611 const char* name = node->getName().c_str();
1612 if (glslang::IsAnonymous(name))
1613 name = "";
1614
1615 return builder.createVariable(storageClass, spvType, name);
1616}
1617
1618// Return type Id of the sampled type.
1619spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1620{
1621 switch (sampler.type) {
1622 case glslang::EbtFloat: return builder.makeFloatType(32);
1623 case glslang::EbtInt: return builder.makeIntType(32);
1624 case glslang::EbtUint: return builder.makeUintType(32);
1625 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001626 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001627 return builder.makeFloatType(32);
1628 }
1629}
1630
John Kessenich3ac051e2015-12-20 11:29:16 -07001631// Convert from a glslang type to an SPV type, by calling into a
1632// recursive version of this function. This establishes the inherited
1633// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001634spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1635{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001636 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001637}
1638
1639// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001640// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001641spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001642{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001643 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001644
1645 switch (type.getBasicType()) {
1646 case glslang::EbtVoid:
1647 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001648 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001649 break;
1650 case glslang::EbtFloat:
1651 spvType = builder.makeFloatType(32);
1652 break;
1653 case glslang::EbtDouble:
1654 spvType = builder.makeFloatType(64);
1655 break;
1656 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001657 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1658 // a 32-bit int where non-0 means true.
1659 if (explicitLayout != glslang::ElpNone)
1660 spvType = builder.makeUintType(32);
1661 else
1662 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001663 break;
1664 case glslang::EbtInt:
1665 spvType = builder.makeIntType(32);
1666 break;
1667 case glslang::EbtUint:
1668 spvType = builder.makeUintType(32);
1669 break;
John Kessenich426394d2015-07-23 10:22:48 -06001670 case glslang::EbtAtomicUint:
1671 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1672 spvType = builder.makeUintType(32);
1673 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001674 case glslang::EbtSampler:
1675 {
1676 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001677 if (sampler.sampler) {
1678 // pure sampler
1679 spvType = builder.makeSamplerType();
1680 } else {
1681 // an image is present, make its type
1682 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1683 sampler.image ? 2 : 1, TranslateImageFormat(type));
1684 if (sampler.combined) {
1685 // already has both image and sampler, make the combined type
1686 spvType = builder.makeSampledImageType(spvType);
1687 }
John Kessenich55e7d112015-11-15 21:33:39 -07001688 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001689 }
John Kessenich140f3df2015-06-26 16:58:36 -06001690 break;
1691 case glslang::EbtStruct:
1692 case glslang::EbtBlock:
1693 {
1694 // If we've seen this struct type, return it
1695 const glslang::TTypeList* glslangStruct = type.getStruct();
1696 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001697
1698 // Try to share structs for different layouts, but not yet for other
1699 // kinds of qualification (primarily not yet including interpolant qualification).
1700 if (! HasNonLayoutQualifiers(qualifier))
1701 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1702 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001703 break;
1704
1705 // else, we haven't seen it...
1706
1707 // Create a vector of struct types for SPIR-V to consume
1708 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1709 if (type.getBasicType() == glslang::EbtBlock)
1710 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001711 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001712 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1713 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1714 if (glslangType.hiddenMember()) {
1715 ++memberDelta;
1716 if (type.getBasicType() == glslang::EbtBlock)
1717 memberRemapper[glslangStruct][i] = -1;
1718 } else {
1719 if (type.getBasicType() == glslang::EbtBlock)
1720 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001721 // modify just this child's view of the qualifier
1722 glslang::TQualifier subQualifier = glslangType.getQualifier();
1723 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001724
1725 // manually inherit location; it's more complex
1726 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1727 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1728 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001729 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001730
1731 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001732 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001733 }
1734 }
1735
1736 // Make the SPIR-V type
1737 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001738 if (! HasNonLayoutQualifiers(qualifier))
1739 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001740
1741 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001742 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001743 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001744 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1745 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1746 int member = i;
1747 if (type.getBasicType() == glslang::EbtBlock)
1748 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001749
John Kesseniche0b6cad2015-12-24 10:30:13 -07001750 // modify just this child's view of the qualifier
1751 glslang::TQualifier subQualifier = glslangType.getQualifier();
1752 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001753
John Kessenich140f3df2015-06-26 16:58:36 -06001754 // using -1 above to indicate a hidden member
1755 if (member >= 0) {
1756 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001757 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001758 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001759 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1760 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001761
1762 // compute location decoration; tricky based on whether inheritance is at play
1763 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1764 // probably move to the linker stage of the front end proper, and just have the
1765 // answer sitting already distributed throughout the individual member locations.
1766 int location = -1; // will only decorate if present or inherited
1767 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1768 location = subQualifier.layoutLocation;
1769 else if (qualifier.hasLocation()) // inheritance
1770 location = qualifier.layoutLocation + locationOffset;
1771 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001772 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001773 if (location >= 0)
1774 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1775
1776 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001777 if (glslangType.getQualifier().hasComponent())
1778 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1779 if (glslangType.getQualifier().hasXfbOffset())
1780 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001781 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001782 // figure out what to do with offset, which is accumulating
1783 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001784 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001785 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001786 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001787 offset = nextOffset;
1788 }
John Kessenich140f3df2015-06-26 16:58:36 -06001789
John Kessenichf85e8062015-12-19 13:57:10 -07001790 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001791 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001792
John Kessenich140f3df2015-06-26 16:58:36 -06001793 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001794 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1795 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001796 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001797 }
1798 }
1799
1800 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001801 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001802 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenich92187592016-02-01 13:45:25 -07001803 if (type.getQualifier().hasStream()) {
1804 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001805 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001806 }
John Kessenich140f3df2015-06-26 16:58:36 -06001807 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001808 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001809 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001810 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001811 if (type.getQualifier().hasXfbBuffer())
1812 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1813 }
1814 }
1815 break;
1816 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001817 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001818 break;
1819 }
1820
1821 if (type.isMatrix())
1822 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1823 else {
1824 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1825 if (type.getVectorSize() > 1)
1826 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1827 }
1828
1829 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001830 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1831
John Kessenichc9a80832015-09-12 12:17:44 -06001832 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001833 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001834 // We need to decorate array strides for types needing explicit layout, except blocks.
1835 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001836 // Use a dummy glslang type for querying internal strides of
1837 // arrays of arrays, but using just a one-dimensional array.
1838 glslang::TType simpleArrayType(type, 0); // deference type of the array
1839 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1840 simpleArrayType.getArraySizes().dereference();
1841
1842 // Will compute the higher-order strides here, rather than making a whole
1843 // pile of types and doing repetitive recursion on their contents.
1844 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1845 }
John Kessenichf8842e52016-01-04 19:22:56 -07001846
1847 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001848 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001849 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001850 if (stride > 0)
1851 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001852 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001853 }
1854 } else {
1855 // single-dimensional array, and don't yet have stride
1856
John Kessenichf8842e52016-01-04 19:22:56 -07001857 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001858 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1859 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001860 }
John Kessenich31ed4832015-09-09 17:51:38 -06001861
John Kessenichc9a80832015-09-12 12:17:44 -06001862 // Do the outer dimension, which might not be known for a runtime-sized array
1863 if (type.isRuntimeSizedArray()) {
1864 spvType = builder.makeRuntimeArray(spvType);
1865 } else {
1866 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001867 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001868 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001869 if (stride > 0)
1870 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001871 }
1872
1873 return spvType;
1874}
1875
John Kessenich6c292d32016-02-15 20:58:50 -07001876// Turn the expression forming the array size into an id.
1877// This is not quite trivial, because of specialization constants.
1878// Sometimes, a raw constant is turned into an Id, and sometimes
1879// a specialization constant expression is.
1880spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1881{
1882 // First, see if this is sized with a node, meaning a specialization constant:
1883 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1884 if (specNode != nullptr) {
1885 builder.clearAccessChain();
1886 specNode->traverse(this);
1887 return accessChainLoad(specNode->getAsTyped()->getType());
1888 }
1889
1890 // Otherwise, need a compile-time (front end) size, get it:
1891 int size = arraySizes.getDimSize(dim);
1892 assert(size > 0);
1893 return builder.makeUintConstant(size);
1894}
1895
John Kessenich103bef92016-02-08 21:38:15 -07001896// Wrap the builder's accessChainLoad to:
1897// - localize handling of RelaxedPrecision
1898// - use the SPIR-V inferred type instead of another conversion of the glslang type
1899// (avoids unnecessary work and possible type punning for structures)
1900// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001901spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1902{
John Kessenich103bef92016-02-08 21:38:15 -07001903 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1904 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1905
1906 // Need to convert to abstract types when necessary
1907 if (builder.isScalarType(nominalTypeId) && type.getBasicType() == glslang::EbtBool && nominalTypeId != builder.makeBoolType())
1908 loadedId = builder.createBinOp(spv::OpINotEqual, builder.makeBoolType(), loadedId, builder.makeUintConstant(0));
1909
1910 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07001911}
1912
John Kessenichf85e8062015-12-19 13:57:10 -07001913// Decide whether or not this type should be
1914// decorated with offsets and strides, and if so
1915// whether std140 or std430 rules should be applied.
1916glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001917{
John Kessenichf85e8062015-12-19 13:57:10 -07001918 // has to be a block
1919 if (type.getBasicType() != glslang::EbtBlock)
1920 return glslang::ElpNone;
1921
1922 // has to be a uniform or buffer block
1923 if (type.getQualifier().storage != glslang::EvqUniform &&
1924 type.getQualifier().storage != glslang::EvqBuffer)
1925 return glslang::ElpNone;
1926
1927 // return the layout to use
1928 switch (type.getQualifier().layoutPacking) {
1929 case glslang::ElpStd140:
1930 case glslang::ElpStd430:
1931 return type.getQualifier().layoutPacking;
1932 default:
1933 return glslang::ElpNone;
1934 }
John Kessenich31ed4832015-09-09 17:51:38 -06001935}
1936
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001937// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001938int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001939{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001940 int size;
John Kessenich49987892015-12-29 17:11:44 -07001941 int stride;
1942 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001943
1944 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001945}
1946
John Kessenich49987892015-12-29 17:11:44 -07001947// 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 -07001948// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001949int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001950{
John Kessenich49987892015-12-29 17:11:44 -07001951 glslang::TType elementType;
1952 elementType.shallowCopy(matrixType);
1953 elementType.clearArraySizes();
1954
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001955 int size;
John Kessenich49987892015-12-29 17:11:44 -07001956 int stride;
1957 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
1958
1959 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001960}
1961
John Kessenich5e4b1242015-08-06 22:53:06 -06001962// Given a member type of a struct, realign the current offset for it, and compute
1963// the next (not yet aligned) offset for the next member, which will get aligned
1964// on the next call.
1965// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1966// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1967// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07001968void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07001969 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06001970{
1971 // this will get a positive value when deemed necessary
1972 nextOffset = -1;
1973
John Kessenich5e4b1242015-08-06 22:53:06 -06001974 // override anything in currentOffset with user-set offset
1975 if (memberType.getQualifier().hasOffset())
1976 currentOffset = memberType.getQualifier().layoutOffset;
1977
1978 // It could be that current linker usage in glslang updated all the layoutOffset,
1979 // in which case the following code does not matter. But, that's not quite right
1980 // once cross-compilation unit GLSL validation is done, as the original user
1981 // settings are needed in layoutOffset, and then the following will come into play.
1982
John Kessenichf85e8062015-12-19 13:57:10 -07001983 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001984 if (! memberType.getQualifier().hasOffset())
1985 currentOffset = -1;
1986
1987 return;
1988 }
1989
John Kessenichf85e8062015-12-19 13:57:10 -07001990 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06001991 if (currentOffset < 0)
1992 currentOffset = 0;
1993
1994 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1995 // but possibly not yet correctly aligned.
1996
1997 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07001998 int dummyStride;
1999 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002000 glslang::RoundToPow2(currentOffset, memberAlignment);
2001 nextOffset = currentOffset + memberSize;
2002}
2003
John Kessenich140f3df2015-06-26 16:58:36 -06002004bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2005{
2006 return node->getName() == "main(";
2007}
2008
2009// Make all the functions, skeletally, without actually visiting their bodies.
2010void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2011{
2012 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2013 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2014 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2015 continue;
2016
2017 // We're on a user function. Set up the basic interface for the function now,
2018 // so that it's available to call.
2019 // Translating the body will happen later.
2020 //
2021 // Typically (except for a "const in" parameter), an address will be passed to the
2022 // function. What it is an address of varies:
2023 //
2024 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2025 // so that write needs to be to a copy, hence the address of a copy works.
2026 //
2027 // - "const in" parameters can just be the r-value, as no writes need occur.
2028 //
2029 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2030 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2031
2032 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002033 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002034 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2035
2036 for (int p = 0; p < (int)parameters.size(); ++p) {
2037 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2038 spv::Id typeId = convertGlslangToSpvType(paramType);
2039 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2040 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2041 else
2042 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002043 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002044 paramTypes.push_back(typeId);
2045 }
2046
2047 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002048 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2049 convertGlslangToSpvType(glslFunction->getType()),
2050 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002051
2052 // Track function to emit/call later
2053 functionMap[glslFunction->getName().c_str()] = function;
2054
2055 // Set the parameter id's
2056 for (int p = 0; p < (int)parameters.size(); ++p) {
2057 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2058 // give a name too
2059 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2060 }
2061 }
2062}
2063
2064// Process all the initializers, while skipping the functions and link objects
2065void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2066{
2067 builder.setBuildPoint(shaderEntry->getLastBlock());
2068 for (int i = 0; i < (int)initializers.size(); ++i) {
2069 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2070 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2071
2072 // We're on a top-level node that's not a function. Treat as an initializer, whose
2073 // code goes into the beginning of main.
2074 initializer->traverse(this);
2075 }
2076 }
2077}
2078
2079// Process all the functions, while skipping initializers.
2080void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2081{
2082 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2083 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2084 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2085 node->traverse(this);
2086 }
2087}
2088
2089void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2090{
2091 // SPIR-V functions should already be in the functionMap from the prepass
2092 // that called makeFunctions().
2093 spv::Function* function = functionMap[node->getName().c_str()];
2094 spv::Block* functionBlock = function->getEntryBlock();
2095 builder.setBuildPoint(functionBlock);
2096}
2097
Rex Xu04db3f52015-09-16 11:44:02 +08002098void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002099{
Rex Xufc618912015-09-09 16:42:49 +08002100 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002101
2102 glslang::TSampler sampler = {};
2103 bool cubeCompare = false;
2104 if (node.isTexture()) {
2105 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2106 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2107 }
2108
John Kessenich140f3df2015-06-26 16:58:36 -06002109 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2110 builder.clearAccessChain();
2111 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002112
2113 // Special case l-value operands
2114 bool lvalue = false;
2115 switch (node.getOp()) {
2116 case glslang::EOpImageAtomicAdd:
2117 case glslang::EOpImageAtomicMin:
2118 case glslang::EOpImageAtomicMax:
2119 case glslang::EOpImageAtomicAnd:
2120 case glslang::EOpImageAtomicOr:
2121 case glslang::EOpImageAtomicXor:
2122 case glslang::EOpImageAtomicExchange:
2123 case glslang::EOpImageAtomicCompSwap:
2124 if (i == 0)
2125 lvalue = true;
2126 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002127 case glslang::EOpSparseTexture:
2128 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2129 lvalue = true;
2130 break;
2131 case glslang::EOpSparseTextureClamp:
2132 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2133 lvalue = true;
2134 break;
2135 case glslang::EOpSparseTextureLod:
2136 case glslang::EOpSparseTextureOffset:
2137 if (i == 3)
2138 lvalue = true;
2139 break;
2140 case glslang::EOpSparseTextureFetch:
2141 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2142 lvalue = true;
2143 break;
2144 case glslang::EOpSparseTextureFetchOffset:
2145 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2146 lvalue = true;
2147 break;
2148 case glslang::EOpSparseTextureLodOffset:
2149 case glslang::EOpSparseTextureGrad:
2150 case glslang::EOpSparseTextureOffsetClamp:
2151 if (i == 4)
2152 lvalue = true;
2153 break;
2154 case glslang::EOpSparseTextureGradOffset:
2155 case glslang::EOpSparseTextureGradClamp:
2156 if (i == 5)
2157 lvalue = true;
2158 break;
2159 case glslang::EOpSparseTextureGradOffsetClamp:
2160 if (i == 6)
2161 lvalue = true;
2162 break;
2163 case glslang::EOpSparseTextureGather:
2164 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2165 lvalue = true;
2166 break;
2167 case glslang::EOpSparseTextureGatherOffset:
2168 case glslang::EOpSparseTextureGatherOffsets:
2169 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2170 lvalue = true;
2171 break;
Rex Xufc618912015-09-09 16:42:49 +08002172 default:
2173 break;
2174 }
2175
Rex Xu6b86d492015-09-16 17:48:22 +08002176 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002177 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002178 else
John Kessenich32cfd492016-02-02 12:37:46 -07002179 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002180 }
2181}
2182
John Kessenichfc51d282015-08-19 13:34:18 -06002183void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002184{
John Kessenichfc51d282015-08-19 13:34:18 -06002185 builder.clearAccessChain();
2186 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002187 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002188}
John Kessenich140f3df2015-06-26 16:58:36 -06002189
John Kessenichfc51d282015-08-19 13:34:18 -06002190spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2191{
Rex Xufc618912015-09-09 16:42:49 +08002192 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002193 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002194 }
2195
John Kessenichfc51d282015-08-19 13:34:18 -06002196 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002197 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2198 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2199 std::vector<spv::Id> arguments;
2200 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002201 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002202 else
2203 translateArguments(*node->getAsUnaryNode(), arguments);
2204 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2205
2206 spv::Builder::TextureParameters params = { };
2207 params.sampler = arguments[0];
2208
Rex Xu04db3f52015-09-16 11:44:02 +08002209 glslang::TCrackedTextureOp cracked;
2210 node->crackTexture(sampler, cracked);
2211
John Kessenichfc51d282015-08-19 13:34:18 -06002212 // Check for queries
2213 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002214 // a sampled image needs to have the image extracted first
2215 if (builder.isSampledImage(params.sampler))
2216 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002217 switch (node->getOp()) {
2218 case glslang::EOpImageQuerySize:
2219 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002220 if (arguments.size() > 1) {
2221 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002222 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002223 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002224 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002225 case glslang::EOpImageQuerySamples:
2226 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002227 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002228 case glslang::EOpTextureQueryLod:
2229 params.coords = arguments[1];
2230 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2231 case glslang::EOpTextureQueryLevels:
2232 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002233 case glslang::EOpSparseTexelsResident:
2234 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002235 default:
2236 assert(0);
2237 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002238 }
John Kessenich140f3df2015-06-26 16:58:36 -06002239 }
2240
Rex Xufc618912015-09-09 16:42:49 +08002241 // Check for image functions other than queries
2242 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002243 std::vector<spv::Id> operands;
2244 auto opIt = arguments.begin();
2245 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002246
2247 // Handle subpass operations
2248 // TODO: GLSL should change to have the "MS" only on the type rather than the
2249 // built-in function.
2250 if (cracked.subpass) {
2251 // add on the (0,0) coordinate
2252 spv::Id zero = builder.makeIntConstant(0);
2253 std::vector<spv::Id> comps;
2254 comps.push_back(zero);
2255 comps.push_back(zero);
2256 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2257 if (sampler.ms) {
2258 operands.push_back(spv::ImageOperandsSampleMask);
2259 operands.push_back(*(opIt++));
2260 }
2261 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2262 }
2263
John Kessenich56bab042015-09-16 10:54:31 -06002264 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002265 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002266 if (sampler.ms) {
2267 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002268 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002269 }
John Kessenich56bab042015-09-16 10:54:31 -06002270 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002271 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2272 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002273 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002274 if (sampler.ms) {
2275 operands.push_back(*(opIt + 1));
2276 operands.push_back(spv::ImageOperandsSampleMask);
2277 operands.push_back(*opIt);
2278 } else
2279 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002280 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002281 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2282 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002283 return spv::NoResult;
Rex Xu48edadf2015-12-31 16:11:41 +08002284 } else if (node->isSparseImage()) {
2285 spv::MissingFunctionality("sparse image functions");
2286 return spv::NoResult;
John Kessenichcd261442016-01-22 09:54:12 -07002287 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002288 // Process image atomic operations
2289
2290 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2291 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002292 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002293
Rex Xufc618912015-09-09 16:42:49 +08002294 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002295 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002296
2297 std::vector<spv::Id> operands;
2298 operands.push_back(pointer);
2299 for (; opIt != arguments.end(); ++opIt)
2300 operands.push_back(*opIt);
2301
Rex Xu04db3f52015-09-16 11:44:02 +08002302 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002303 }
2304 }
2305
2306 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002307 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002308 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2309
John Kessenichfc51d282015-08-19 13:34:18 -06002310 // check for bias argument
2311 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002312 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002313 int nonBiasArgCount = 2;
2314 if (cracked.offset)
2315 ++nonBiasArgCount;
2316 if (cracked.grad)
2317 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002318 if (cracked.lodClamp)
2319 ++nonBiasArgCount;
2320 if (sparse)
2321 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002322
2323 if ((int)arguments.size() > nonBiasArgCount)
2324 bias = true;
2325 }
2326
John Kessenichfc51d282015-08-19 13:34:18 -06002327 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002328
John Kessenichfc51d282015-08-19 13:34:18 -06002329 params.coords = arguments[1];
2330 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002331 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002332
2333 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002334 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002335 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002336 ++extraArgs;
2337 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002338 params.Dref = arguments[2];
2339 ++extraArgs;
2340 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002341 std::vector<spv::Id> indexes;
2342 int comp;
2343 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002344 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002345 else
2346 comp = builder.getNumComponents(params.coords) - 1;
2347 indexes.push_back(comp);
2348 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2349 }
2350 if (cracked.lod) {
2351 params.lod = arguments[2];
2352 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002353 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2354 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2355 noImplicitLod = true;
2356 }
2357 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002358 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002359 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002360 }
2361 if (cracked.grad) {
2362 params.gradX = arguments[2 + extraArgs];
2363 params.gradY = arguments[3 + extraArgs];
2364 extraArgs += 2;
2365 }
John Kessenich55e7d112015-11-15 21:33:39 -07002366 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002367 params.offset = arguments[2 + extraArgs];
2368 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002369 } else if (cracked.offsets) {
2370 params.offsets = arguments[2 + extraArgs];
2371 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002372 }
Rex Xu48edadf2015-12-31 16:11:41 +08002373 if (cracked.lodClamp) {
2374 params.lodClamp = arguments[2 + extraArgs];
2375 ++extraArgs;
2376 }
2377 if (sparse) {
2378 params.texelOut = arguments[2 + extraArgs];
2379 ++extraArgs;
2380 }
John Kessenichfc51d282015-08-19 13:34:18 -06002381 if (bias) {
2382 params.bias = arguments[2 + extraArgs];
2383 ++extraArgs;
2384 }
John Kessenich55e7d112015-11-15 21:33:39 -07002385 if (cracked.gather && ! sampler.shadow) {
2386 // default component is 0, if missing, otherwise an argument
2387 if (2 + extraArgs < (int)arguments.size()) {
2388 params.comp = arguments[2 + extraArgs];
2389 ++extraArgs;
2390 } else {
2391 params.comp = builder.makeIntConstant(0);
2392 }
2393 }
John Kessenichfc51d282015-08-19 13:34:18 -06002394
John Kessenich019f08f2016-02-15 15:40:42 -07002395 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002396}
2397
2398spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2399{
2400 // Grab the function's pointer from the previously created function
2401 spv::Function* function = functionMap[node->getName().c_str()];
2402 if (! function)
2403 return 0;
2404
2405 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2406 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2407
2408 // See comments in makeFunctions() for details about the semantics for parameter passing.
2409 //
2410 // These imply we need a four step process:
2411 // 1. Evaluate the arguments
2412 // 2. Allocate and make copies of in, out, and inout arguments
2413 // 3. Make the call
2414 // 4. Copy back the results
2415
2416 // 1. Evaluate the arguments
2417 std::vector<spv::Builder::AccessChain> lValues;
2418 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002419 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002420 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2421 // build l-value
2422 builder.clearAccessChain();
2423 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002424 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002425 // keep outputs as l-values, evaluate input-only as r-values
2426 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2427 // save l-value
2428 lValues.push_back(builder.getAccessChain());
2429 } else {
2430 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002431 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002432 }
2433 }
2434
2435 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2436 // copy the original into that space.
2437 //
2438 // Also, build up the list of actual arguments to pass in for the call
2439 int lValueCount = 0;
2440 int rValueCount = 0;
2441 std::vector<spv::Id> spvArgs;
2442 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2443 spv::Id arg;
2444 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2445 // need space to hold the copy
2446 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2447 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2448 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2449 // need to copy the input into output space
2450 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002451 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002452 builder.createStore(copy, arg);
2453 }
2454 ++lValueCount;
2455 } else {
2456 arg = rValues[rValueCount];
2457 ++rValueCount;
2458 }
2459 spvArgs.push_back(arg);
2460 }
2461
2462 // 3. Make the call.
2463 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002464 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002465
2466 // 4. Copy back out an "out" arguments.
2467 lValueCount = 0;
2468 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2469 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2470 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2471 spv::Id copy = builder.createLoad(spvArgs[a]);
2472 builder.setAccessChain(lValues[lValueCount]);
2473 builder.accessChainStore(copy);
2474 }
2475 ++lValueCount;
2476 }
2477 }
2478
2479 return result;
2480}
2481
2482// Translate AST operation to SPV operation, already having SPV-based operands/types.
2483spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2484 spv::Id typeId, spv::Id left, spv::Id right,
2485 glslang::TBasicType typeProxy, bool reduceComparison)
2486{
2487 bool isUnsigned = typeProxy == glslang::EbtUint;
2488 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2489
2490 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002491 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002492 bool comparison = false;
2493
2494 switch (op) {
2495 case glslang::EOpAdd:
2496 case glslang::EOpAddAssign:
2497 if (isFloat)
2498 binOp = spv::OpFAdd;
2499 else
2500 binOp = spv::OpIAdd;
2501 break;
2502 case glslang::EOpSub:
2503 case glslang::EOpSubAssign:
2504 if (isFloat)
2505 binOp = spv::OpFSub;
2506 else
2507 binOp = spv::OpISub;
2508 break;
2509 case glslang::EOpMul:
2510 case glslang::EOpMulAssign:
2511 if (isFloat)
2512 binOp = spv::OpFMul;
2513 else
2514 binOp = spv::OpIMul;
2515 break;
2516 case glslang::EOpVectorTimesScalar:
2517 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002518 if (isFloat) {
2519 if (builder.isVector(right))
2520 std::swap(left, right);
2521 assert(builder.isScalar(right));
2522 needMatchingVectors = false;
2523 binOp = spv::OpVectorTimesScalar;
2524 } else
2525 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002526 break;
2527 case glslang::EOpVectorTimesMatrix:
2528 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002529 binOp = spv::OpVectorTimesMatrix;
2530 break;
2531 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002532 binOp = spv::OpMatrixTimesVector;
2533 break;
2534 case glslang::EOpMatrixTimesScalar:
2535 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002536 binOp = spv::OpMatrixTimesScalar;
2537 break;
2538 case glslang::EOpMatrixTimesMatrix:
2539 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002540 binOp = spv::OpMatrixTimesMatrix;
2541 break;
2542 case glslang::EOpOuterProduct:
2543 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002544 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002545 break;
2546
2547 case glslang::EOpDiv:
2548 case glslang::EOpDivAssign:
2549 if (isFloat)
2550 binOp = spv::OpFDiv;
2551 else if (isUnsigned)
2552 binOp = spv::OpUDiv;
2553 else
2554 binOp = spv::OpSDiv;
2555 break;
2556 case glslang::EOpMod:
2557 case glslang::EOpModAssign:
2558 if (isFloat)
2559 binOp = spv::OpFMod;
2560 else if (isUnsigned)
2561 binOp = spv::OpUMod;
2562 else
2563 binOp = spv::OpSMod;
2564 break;
2565 case glslang::EOpRightShift:
2566 case glslang::EOpRightShiftAssign:
2567 if (isUnsigned)
2568 binOp = spv::OpShiftRightLogical;
2569 else
2570 binOp = spv::OpShiftRightArithmetic;
2571 break;
2572 case glslang::EOpLeftShift:
2573 case glslang::EOpLeftShiftAssign:
2574 binOp = spv::OpShiftLeftLogical;
2575 break;
2576 case glslang::EOpAnd:
2577 case glslang::EOpAndAssign:
2578 binOp = spv::OpBitwiseAnd;
2579 break;
2580 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002581 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002582 binOp = spv::OpLogicalAnd;
2583 break;
2584 case glslang::EOpInclusiveOr:
2585 case glslang::EOpInclusiveOrAssign:
2586 binOp = spv::OpBitwiseOr;
2587 break;
2588 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002589 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002590 binOp = spv::OpLogicalOr;
2591 break;
2592 case glslang::EOpExclusiveOr:
2593 case glslang::EOpExclusiveOrAssign:
2594 binOp = spv::OpBitwiseXor;
2595 break;
2596 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002597 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002598 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002599 break;
2600
2601 case glslang::EOpLessThan:
2602 case glslang::EOpGreaterThan:
2603 case glslang::EOpLessThanEqual:
2604 case glslang::EOpGreaterThanEqual:
2605 case glslang::EOpEqual:
2606 case glslang::EOpNotEqual:
2607 case glslang::EOpVectorEqual:
2608 case glslang::EOpVectorNotEqual:
2609 comparison = true;
2610 break;
2611 default:
2612 break;
2613 }
2614
John Kessenich7c1aa102015-10-15 13:29:11 -06002615 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002616 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002617 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002618 if (builder.isMatrix(left) || builder.isMatrix(right))
2619 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002620
2621 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002622 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002623 builder.promoteScalar(precision, left, right);
2624
John Kessenich32cfd492016-02-02 12:37:46 -07002625 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002626 }
2627
2628 if (! comparison)
2629 return 0;
2630
John Kessenich7c1aa102015-10-15 13:29:11 -06002631 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002632
2633 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2634 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2635
John Kessenich22118352015-12-21 20:54:09 -07002636 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002637 }
2638
2639 switch (op) {
2640 case glslang::EOpLessThan:
2641 if (isFloat)
2642 binOp = spv::OpFOrdLessThan;
2643 else if (isUnsigned)
2644 binOp = spv::OpULessThan;
2645 else
2646 binOp = spv::OpSLessThan;
2647 break;
2648 case glslang::EOpGreaterThan:
2649 if (isFloat)
2650 binOp = spv::OpFOrdGreaterThan;
2651 else if (isUnsigned)
2652 binOp = spv::OpUGreaterThan;
2653 else
2654 binOp = spv::OpSGreaterThan;
2655 break;
2656 case glslang::EOpLessThanEqual:
2657 if (isFloat)
2658 binOp = spv::OpFOrdLessThanEqual;
2659 else if (isUnsigned)
2660 binOp = spv::OpULessThanEqual;
2661 else
2662 binOp = spv::OpSLessThanEqual;
2663 break;
2664 case glslang::EOpGreaterThanEqual:
2665 if (isFloat)
2666 binOp = spv::OpFOrdGreaterThanEqual;
2667 else if (isUnsigned)
2668 binOp = spv::OpUGreaterThanEqual;
2669 else
2670 binOp = spv::OpSGreaterThanEqual;
2671 break;
2672 case glslang::EOpEqual:
2673 case glslang::EOpVectorEqual:
2674 if (isFloat)
2675 binOp = spv::OpFOrdEqual;
2676 else
2677 binOp = spv::OpIEqual;
2678 break;
2679 case glslang::EOpNotEqual:
2680 case glslang::EOpVectorNotEqual:
2681 if (isFloat)
2682 binOp = spv::OpFOrdNotEqual;
2683 else
2684 binOp = spv::OpINotEqual;
2685 break;
2686 default:
2687 break;
2688 }
2689
John Kessenich32cfd492016-02-02 12:37:46 -07002690 if (binOp != spv::OpNop)
2691 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002692
2693 return 0;
2694}
2695
John Kessenich04bb8a02015-12-12 12:28:14 -07002696//
2697// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2698// These can be any of:
2699//
2700// matrix * scalar
2701// scalar * matrix
2702// matrix * matrix linear algebraic
2703// matrix * vector
2704// vector * matrix
2705// matrix * matrix componentwise
2706// matrix op matrix op in {+, -, /}
2707// matrix op scalar op in {+, -, /}
2708// scalar op matrix op in {+, -, /}
2709//
2710spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2711{
2712 bool firstClass = true;
2713
2714 // First, handle first-class matrix operations (* and matrix/scalar)
2715 switch (op) {
2716 case spv::OpFDiv:
2717 if (builder.isMatrix(left) && builder.isScalar(right)) {
2718 // turn matrix / scalar into a multiply...
2719 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2720 op = spv::OpMatrixTimesScalar;
2721 } else
2722 firstClass = false;
2723 break;
2724 case spv::OpMatrixTimesScalar:
2725 if (builder.isMatrix(right))
2726 std::swap(left, right);
2727 assert(builder.isScalar(right));
2728 break;
2729 case spv::OpVectorTimesMatrix:
2730 assert(builder.isVector(left));
2731 assert(builder.isMatrix(right));
2732 break;
2733 case spv::OpMatrixTimesVector:
2734 assert(builder.isMatrix(left));
2735 assert(builder.isVector(right));
2736 break;
2737 case spv::OpMatrixTimesMatrix:
2738 assert(builder.isMatrix(left));
2739 assert(builder.isMatrix(right));
2740 break;
2741 default:
2742 firstClass = false;
2743 break;
2744 }
2745
John Kessenich32cfd492016-02-02 12:37:46 -07002746 if (firstClass)
2747 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002748
2749 // Handle component-wise +, -, *, and / for all combinations of type.
2750 // The result type of all of them is the same type as the (a) matrix operand.
2751 // The algorithm is to:
2752 // - break the matrix(es) into vectors
2753 // - smear any scalar to a vector
2754 // - do vector operations
2755 // - make a matrix out the vector results
2756 switch (op) {
2757 case spv::OpFAdd:
2758 case spv::OpFSub:
2759 case spv::OpFDiv:
2760 case spv::OpFMul:
2761 {
2762 // one time set up...
2763 bool leftMat = builder.isMatrix(left);
2764 bool rightMat = builder.isMatrix(right);
2765 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2766 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2767 spv::Id scalarType = builder.getScalarTypeId(typeId);
2768 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2769 std::vector<spv::Id> results;
2770 spv::Id smearVec = spv::NoResult;
2771 if (builder.isScalar(left))
2772 smearVec = builder.smearScalar(precision, left, vecType);
2773 else if (builder.isScalar(right))
2774 smearVec = builder.smearScalar(precision, right, vecType);
2775
2776 // do each vector op
2777 for (unsigned int c = 0; c < numCols; ++c) {
2778 std::vector<unsigned int> indexes;
2779 indexes.push_back(c);
2780 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2781 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2782 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2783 builder.setPrecision(results.back(), precision);
2784 }
2785
2786 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002787 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002788 }
2789 default:
2790 assert(0);
2791 return spv::NoResult;
2792 }
2793}
2794
Rex Xu04db3f52015-09-16 11:44:02 +08002795spv::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 -06002796{
2797 spv::Op unaryOp = spv::OpNop;
2798 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002799 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002800 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002801
2802 switch (op) {
2803 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002804 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002805 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002806 if (builder.isMatrixType(typeId))
2807 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2808 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002809 unaryOp = spv::OpSNegate;
2810 break;
2811
2812 case glslang::EOpLogicalNot:
2813 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002814 unaryOp = spv::OpLogicalNot;
2815 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002816 case glslang::EOpBitwiseNot:
2817 unaryOp = spv::OpNot;
2818 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002819
John Kessenich140f3df2015-06-26 16:58:36 -06002820 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002821 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002822 break;
2823 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002824 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002825 break;
2826 case glslang::EOpTranspose:
2827 unaryOp = spv::OpTranspose;
2828 break;
2829
2830 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002831 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002832 break;
2833 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002834 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002835 break;
2836 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002837 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002838 break;
2839 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002840 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002841 break;
2842 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002843 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002844 break;
2845 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002846 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002847 break;
2848 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002849 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002850 break;
2851 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002852 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002853 break;
2854
2855 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002856 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002857 break;
2858 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002859 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002860 break;
2861 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002862 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002863 break;
2864 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002865 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002866 break;
2867 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002868 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002869 break;
2870 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002871 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002872 break;
2873
2874 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002875 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002876 break;
2877 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002878 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002879 break;
2880
2881 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002882 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002883 break;
2884 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002885 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002886 break;
2887 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002888 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002889 break;
2890 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002891 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002892 break;
2893 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002894 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002895 break;
2896 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002897 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002898 break;
2899
2900 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002901 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002902 break;
2903 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002904 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002905 break;
2906 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002907 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002908 break;
2909 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002910 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002911 break;
2912 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002913 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002914 break;
2915 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002916 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002917 break;
2918
2919 case glslang::EOpIsNan:
2920 unaryOp = spv::OpIsNan;
2921 break;
2922 case glslang::EOpIsInf:
2923 unaryOp = spv::OpIsInf;
2924 break;
2925
Rex Xucbc426e2015-12-15 16:03:10 +08002926 case glslang::EOpFloatBitsToInt:
2927 case glslang::EOpFloatBitsToUint:
2928 case glslang::EOpIntBitsToFloat:
2929 case glslang::EOpUintBitsToFloat:
2930 unaryOp = spv::OpBitcast;
2931 break;
2932
John Kessenich140f3df2015-06-26 16:58:36 -06002933 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002934 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002935 break;
2936 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002937 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002938 break;
2939 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002940 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002941 break;
2942 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002943 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002944 break;
2945 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002946 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002947 break;
2948 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002949 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002950 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002951 case glslang::EOpPackSnorm4x8:
2952 libCall = spv::GLSLstd450PackSnorm4x8;
2953 break;
2954 case glslang::EOpUnpackSnorm4x8:
2955 libCall = spv::GLSLstd450UnpackSnorm4x8;
2956 break;
2957 case glslang::EOpPackUnorm4x8:
2958 libCall = spv::GLSLstd450PackUnorm4x8;
2959 break;
2960 case glslang::EOpUnpackUnorm4x8:
2961 libCall = spv::GLSLstd450UnpackUnorm4x8;
2962 break;
2963 case glslang::EOpPackDouble2x32:
2964 libCall = spv::GLSLstd450PackDouble2x32;
2965 break;
2966 case glslang::EOpUnpackDouble2x32:
2967 libCall = spv::GLSLstd450UnpackDouble2x32;
2968 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002969
2970 case glslang::EOpDPdx:
2971 unaryOp = spv::OpDPdx;
2972 break;
2973 case glslang::EOpDPdy:
2974 unaryOp = spv::OpDPdy;
2975 break;
2976 case glslang::EOpFwidth:
2977 unaryOp = spv::OpFwidth;
2978 break;
2979 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07002980 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002981 unaryOp = spv::OpDPdxFine;
2982 break;
2983 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07002984 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002985 unaryOp = spv::OpDPdyFine;
2986 break;
2987 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07002988 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002989 unaryOp = spv::OpFwidthFine;
2990 break;
2991 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002992 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002993 unaryOp = spv::OpDPdxCoarse;
2994 break;
2995 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002996 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002997 unaryOp = spv::OpDPdyCoarse;
2998 break;
2999 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003000 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003001 unaryOp = spv::OpFwidthCoarse;
3002 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003003 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003004 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003005 libCall = spv::GLSLstd450InterpolateAtCentroid;
3006 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003007 case glslang::EOpAny:
3008 unaryOp = spv::OpAny;
3009 break;
3010 case glslang::EOpAll:
3011 unaryOp = spv::OpAll;
3012 break;
3013
3014 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003015 if (isFloat)
3016 libCall = spv::GLSLstd450FAbs;
3017 else
3018 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003019 break;
3020 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003021 if (isFloat)
3022 libCall = spv::GLSLstd450FSign;
3023 else
3024 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003025 break;
3026
John Kessenichfc51d282015-08-19 13:34:18 -06003027 case glslang::EOpAtomicCounterIncrement:
3028 case glslang::EOpAtomicCounterDecrement:
3029 case glslang::EOpAtomicCounter:
3030 {
3031 // Handle all of the atomics in one place, in createAtomicOperation()
3032 std::vector<spv::Id> operands;
3033 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003034 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003035 }
3036
John Kessenichfc51d282015-08-19 13:34:18 -06003037 case glslang::EOpBitFieldReverse:
3038 unaryOp = spv::OpBitReverse;
3039 break;
3040 case glslang::EOpBitCount:
3041 unaryOp = spv::OpBitCount;
3042 break;
3043 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003044 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003045 break;
3046 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003047 if (isUnsigned)
3048 libCall = spv::GLSLstd450FindUMsb;
3049 else
3050 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003051 break;
3052
John Kessenich140f3df2015-06-26 16:58:36 -06003053 default:
3054 return 0;
3055 }
3056
3057 spv::Id id;
3058 if (libCall >= 0) {
3059 std::vector<spv::Id> args;
3060 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003061 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003062 } else
3063 id = builder.createUnaryOp(unaryOp, typeId, operand);
3064
John Kessenich32cfd492016-02-02 12:37:46 -07003065 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003066}
3067
John Kessenich7a53f762016-01-20 11:19:27 -07003068// Create a unary operation on a matrix
3069spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3070{
3071 // Handle unary operations vector by vector.
3072 // The result type is the same type as the original type.
3073 // The algorithm is to:
3074 // - break the matrix into vectors
3075 // - apply the operation to each vector
3076 // - make a matrix out the vector results
3077
3078 // get the types sorted out
3079 int numCols = builder.getNumColumns(operand);
3080 int numRows = builder.getNumRows(operand);
3081 spv::Id scalarType = builder.getScalarTypeId(typeId);
3082 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3083 std::vector<spv::Id> results;
3084
3085 // do each vector op
3086 for (int c = 0; c < numCols; ++c) {
3087 std::vector<unsigned int> indexes;
3088 indexes.push_back(c);
3089 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3090 results.push_back(builder.createUnaryOp(op, vecType, vec));
3091 builder.setPrecision(results.back(), precision);
3092 }
3093
3094 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003095 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003096}
3097
John Kessenich140f3df2015-06-26 16:58:36 -06003098spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3099{
3100 spv::Op convOp = spv::OpNop;
3101 spv::Id zero = 0;
3102 spv::Id one = 0;
3103
3104 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3105
3106 switch (op) {
3107 case glslang::EOpConvIntToBool:
3108 case glslang::EOpConvUintToBool:
3109 zero = builder.makeUintConstant(0);
3110 zero = makeSmearedConstant(zero, vectorSize);
3111 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3112
3113 case glslang::EOpConvFloatToBool:
3114 zero = builder.makeFloatConstant(0.0F);
3115 zero = makeSmearedConstant(zero, vectorSize);
3116 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3117
3118 case glslang::EOpConvDoubleToBool:
3119 zero = builder.makeDoubleConstant(0.0);
3120 zero = makeSmearedConstant(zero, vectorSize);
3121 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3122
3123 case glslang::EOpConvBoolToFloat:
3124 convOp = spv::OpSelect;
3125 zero = builder.makeFloatConstant(0.0);
3126 one = builder.makeFloatConstant(1.0);
3127 break;
3128 case glslang::EOpConvBoolToDouble:
3129 convOp = spv::OpSelect;
3130 zero = builder.makeDoubleConstant(0.0);
3131 one = builder.makeDoubleConstant(1.0);
3132 break;
3133 case glslang::EOpConvBoolToInt:
3134 zero = builder.makeIntConstant(0);
3135 one = builder.makeIntConstant(1);
3136 convOp = spv::OpSelect;
3137 break;
3138 case glslang::EOpConvBoolToUint:
3139 zero = builder.makeUintConstant(0);
3140 one = builder.makeUintConstant(1);
3141 convOp = spv::OpSelect;
3142 break;
3143
3144 case glslang::EOpConvIntToFloat:
3145 case glslang::EOpConvIntToDouble:
3146 convOp = spv::OpConvertSToF;
3147 break;
3148
3149 case glslang::EOpConvUintToFloat:
3150 case glslang::EOpConvUintToDouble:
3151 convOp = spv::OpConvertUToF;
3152 break;
3153
3154 case glslang::EOpConvDoubleToFloat:
3155 case glslang::EOpConvFloatToDouble:
3156 convOp = spv::OpFConvert;
3157 break;
3158
3159 case glslang::EOpConvFloatToInt:
3160 case glslang::EOpConvDoubleToInt:
3161 convOp = spv::OpConvertFToS;
3162 break;
3163
3164 case glslang::EOpConvUintToInt:
3165 case glslang::EOpConvIntToUint:
3166 convOp = spv::OpBitcast;
3167 break;
3168
3169 case glslang::EOpConvFloatToUint:
3170 case glslang::EOpConvDoubleToUint:
3171 convOp = spv::OpConvertFToU;
3172 break;
3173 default:
3174 break;
3175 }
3176
3177 spv::Id result = 0;
3178 if (convOp == spv::OpNop)
3179 return result;
3180
3181 if (convOp == spv::OpSelect) {
3182 zero = makeSmearedConstant(zero, vectorSize);
3183 one = makeSmearedConstant(one, vectorSize);
3184 result = builder.createTriOp(convOp, destType, operand, one, zero);
3185 } else
3186 result = builder.createUnaryOp(convOp, destType, operand);
3187
John Kessenich32cfd492016-02-02 12:37:46 -07003188 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003189}
3190
3191spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3192{
3193 if (vectorSize == 0)
3194 return constant;
3195
3196 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3197 std::vector<spv::Id> components;
3198 for (int c = 0; c < vectorSize; ++c)
3199 components.push_back(constant);
3200 return builder.makeCompositeConstant(vectorTypeId, components);
3201}
3202
John Kessenich426394d2015-07-23 10:22:48 -06003203// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003204spv::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 -06003205{
3206 spv::Op opCode = spv::OpNop;
3207
3208 switch (op) {
3209 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003210 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003211 opCode = spv::OpAtomicIAdd;
3212 break;
3213 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003214 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003215 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003216 break;
3217 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003218 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003219 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003220 break;
3221 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003222 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003223 opCode = spv::OpAtomicAnd;
3224 break;
3225 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003226 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003227 opCode = spv::OpAtomicOr;
3228 break;
3229 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003230 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003231 opCode = spv::OpAtomicXor;
3232 break;
3233 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003234 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003235 opCode = spv::OpAtomicExchange;
3236 break;
3237 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003238 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003239 opCode = spv::OpAtomicCompareExchange;
3240 break;
3241 case glslang::EOpAtomicCounterIncrement:
3242 opCode = spv::OpAtomicIIncrement;
3243 break;
3244 case glslang::EOpAtomicCounterDecrement:
3245 opCode = spv::OpAtomicIDecrement;
3246 break;
3247 case glslang::EOpAtomicCounter:
3248 opCode = spv::OpAtomicLoad;
3249 break;
3250 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003251 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003252 break;
3253 }
3254
3255 // Sort out the operands
3256 // - mapping from glslang -> SPV
3257 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003258 // - compare-exchange swaps the value and comparator
3259 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003260 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3261 auto opIt = operands.begin(); // walk the glslang operands
3262 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003263 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3264 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3265 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003266 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3267 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003268 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003269 spvAtomicOperands.push_back(*(opIt + 1));
3270 spvAtomicOperands.push_back(*opIt);
3271 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003272 }
John Kessenich426394d2015-07-23 10:22:48 -06003273
John Kessenich3e60a6f2015-09-14 22:45:16 -06003274 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003275 for (; opIt != operands.end(); ++opIt)
3276 spvAtomicOperands.push_back(*opIt);
3277
3278 return builder.createOp(opCode, typeId, spvAtomicOperands);
3279}
3280
John Kessenich5e4b1242015-08-06 22:53:06 -06003281spv::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 -06003282{
John Kessenich5e4b1242015-08-06 22:53:06 -06003283 bool isUnsigned = typeProxy == glslang::EbtUint;
3284 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3285
John Kessenich140f3df2015-06-26 16:58:36 -06003286 spv::Op opCode = spv::OpNop;
3287 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003288 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003289 spv::Id typeId0 = 0;
3290 if (consumedOperands > 0)
3291 typeId0 = builder.getTypeId(operands[0]);
3292 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003293
3294 switch (op) {
3295 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003296 if (isFloat)
3297 libCall = spv::GLSLstd450FMin;
3298 else if (isUnsigned)
3299 libCall = spv::GLSLstd450UMin;
3300 else
3301 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003302 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003303 break;
3304 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003305 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003306 break;
3307 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003308 if (isFloat)
3309 libCall = spv::GLSLstd450FMax;
3310 else if (isUnsigned)
3311 libCall = spv::GLSLstd450UMax;
3312 else
3313 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003314 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003315 break;
3316 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003317 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003318 break;
3319 case glslang::EOpDot:
3320 opCode = spv::OpDot;
3321 break;
3322 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003323 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003324 break;
3325
3326 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003327 if (isFloat)
3328 libCall = spv::GLSLstd450FClamp;
3329 else if (isUnsigned)
3330 libCall = spv::GLSLstd450UClamp;
3331 else
3332 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003333 builder.promoteScalar(precision, operands.front(), operands[1]);
3334 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003335 break;
3336 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003337 if (isFloat)
3338 libCall = spv::GLSLstd450FMix;
John Kessenich6c292d32016-02-15 20:58:50 -07003339 else {
3340 opCode = spv::OpSelect;
3341 spv::MissingFunctionality("translating integer mix to OpSelect");
3342 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003343 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003344 break;
3345 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003346 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003347 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003348 break;
3349 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003350 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003351 builder.promoteScalar(precision, operands[0], operands[2]);
3352 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003353 break;
3354
3355 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003356 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003357 break;
3358 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003359 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003360 break;
3361 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003362 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003363 break;
3364 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003365 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003366 break;
3367 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003368 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003369 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003370 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003371 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003372 libCall = spv::GLSLstd450InterpolateAtSample;
3373 break;
3374 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003375 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003376 libCall = spv::GLSLstd450InterpolateAtOffset;
3377 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003378 case glslang::EOpAddCarry:
3379 opCode = spv::OpIAddCarry;
3380 typeId = builder.makeStructResultType(typeId0, typeId0);
3381 consumedOperands = 2;
3382 break;
3383 case glslang::EOpSubBorrow:
3384 opCode = spv::OpISubBorrow;
3385 typeId = builder.makeStructResultType(typeId0, typeId0);
3386 consumedOperands = 2;
3387 break;
3388 case glslang::EOpUMulExtended:
3389 opCode = spv::OpUMulExtended;
3390 typeId = builder.makeStructResultType(typeId0, typeId0);
3391 consumedOperands = 2;
3392 break;
3393 case glslang::EOpIMulExtended:
3394 opCode = spv::OpSMulExtended;
3395 typeId = builder.makeStructResultType(typeId0, typeId0);
3396 consumedOperands = 2;
3397 break;
3398 case glslang::EOpBitfieldExtract:
3399 if (isUnsigned)
3400 opCode = spv::OpBitFieldUExtract;
3401 else
3402 opCode = spv::OpBitFieldSExtract;
3403 break;
3404 case glslang::EOpBitfieldInsert:
3405 opCode = spv::OpBitFieldInsert;
3406 break;
3407
3408 case glslang::EOpFma:
3409 libCall = spv::GLSLstd450Fma;
3410 break;
3411 case glslang::EOpFrexp:
3412 libCall = spv::GLSLstd450FrexpStruct;
3413 if (builder.getNumComponents(operands[0]) == 1)
3414 frexpIntType = builder.makeIntegerType(32, true);
3415 else
3416 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3417 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3418 consumedOperands = 1;
3419 break;
3420 case glslang::EOpLdexp:
3421 libCall = spv::GLSLstd450Ldexp;
3422 break;
3423
John Kessenich140f3df2015-06-26 16:58:36 -06003424 default:
3425 return 0;
3426 }
3427
3428 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003429 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003430 // Use an extended instruction from the standard library.
3431 // Construct the call arguments, without modifying the original operands vector.
3432 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3433 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003434 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003435 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003436 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003437 case 0:
3438 // should all be handled by visitAggregate and createNoArgOperation
3439 assert(0);
3440 return 0;
3441 case 1:
3442 // should all be handled by createUnaryOperation
3443 assert(0);
3444 return 0;
3445 case 2:
3446 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3447 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003448 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003449 // anything 3 or over doesn't have l-value operands, so all should be consumed
3450 assert(consumedOperands == operands.size());
3451 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003452 break;
3453 }
3454 }
3455
John Kessenich55e7d112015-11-15 21:33:39 -07003456 // Decode the return types that were structures
3457 switch (op) {
3458 case glslang::EOpAddCarry:
3459 case glslang::EOpSubBorrow:
3460 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3461 id = builder.createCompositeExtract(id, typeId0, 0);
3462 break;
3463 case glslang::EOpUMulExtended:
3464 case glslang::EOpIMulExtended:
3465 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3466 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3467 break;
3468 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003469 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003470 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3471 id = builder.createCompositeExtract(id, typeId0, 0);
3472 break;
3473 default:
3474 break;
3475 }
3476
John Kessenich32cfd492016-02-02 12:37:46 -07003477 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003478}
3479
3480// Intrinsics with no arguments, no return value, and no precision.
3481spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3482{
3483 // TODO: get the barrier operands correct
3484
3485 switch (op) {
3486 case glslang::EOpEmitVertex:
3487 builder.createNoResultOp(spv::OpEmitVertex);
3488 return 0;
3489 case glslang::EOpEndPrimitive:
3490 builder.createNoResultOp(spv::OpEndPrimitive);
3491 return 0;
3492 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003493 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3494 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003495 return 0;
3496 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003497 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003498 return 0;
3499 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003500 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003501 return 0;
3502 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003503 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003504 return 0;
3505 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003506 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003507 return 0;
3508 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003509 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003510 return 0;
3511 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003512 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003513 return 0;
3514 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003515 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003516 return 0;
3517 }
3518}
3519
3520spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3521{
John Kessenich2f273362015-07-18 22:34:27 -06003522 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003523 spv::Id id;
3524 if (symbolValues.end() != iter) {
3525 id = iter->second;
3526 return id;
3527 }
3528
3529 // it was not found, create it
3530 id = createSpvVariable(symbol);
3531 symbolValues[symbol->getId()] = id;
3532
3533 if (! symbol->getType().isStruct()) {
3534 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003535 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003536 if (symbol->getType().getQualifier().hasSpecConstantId())
3537 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003538 if (symbol->getQualifier().hasLocation())
3539 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3540 if (symbol->getQualifier().hasIndex())
3541 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3542 if (symbol->getQualifier().hasComponent())
3543 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3544 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003545 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003546 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003547 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003548 if (symbol->getQualifier().hasXfbBuffer())
3549 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3550 if (symbol->getQualifier().hasXfbOffset())
3551 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3552 }
3553 }
3554
John Kesseniche0b6cad2015-12-24 10:30:13 -07003555 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenich92187592016-02-01 13:45:25 -07003556 if (symbol->getQualifier().hasStream()) {
3557 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003558 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003559 }
John Kessenich140f3df2015-06-26 16:58:36 -06003560 if (symbol->getQualifier().hasSet())
3561 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003562 else if (IsDescriptorResource(symbol->getType())) {
3563 // default to 0
3564 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3565 }
John Kessenich140f3df2015-06-26 16:58:36 -06003566 if (symbol->getQualifier().hasBinding())
3567 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003568 if (symbol->getQualifier().hasAttachment())
3569 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003570 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003571 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003572 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003573 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003574 if (symbol->getQualifier().hasXfbBuffer())
3575 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3576 }
3577
3578 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003579 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003580 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003581 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003582
John Kessenich140f3df2015-06-26 16:58:36 -06003583 return id;
3584}
3585
John Kessenich55e7d112015-11-15 21:33:39 -07003586// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003587void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3588{
3589 if (dec != spv::BadValue)
3590 builder.addDecoration(id, dec);
3591}
3592
John Kessenich55e7d112015-11-15 21:33:39 -07003593// If 'dec' is valid, add a one-operand decoration to an object
3594void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3595{
3596 if (dec != spv::BadValue)
3597 builder.addDecoration(id, dec, value);
3598}
3599
3600// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003601void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3602{
3603 if (dec != spv::BadValue)
3604 builder.addMemberDecoration(id, (unsigned)member, dec);
3605}
3606
John Kessenich92187592016-02-01 13:45:25 -07003607// If 'dec' is valid, add a one-operand decoration to a struct member
3608void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3609{
3610 if (dec != spv::BadValue)
3611 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3612}
3613
John Kessenich55e7d112015-11-15 21:33:39 -07003614// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003615// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003616//
3617// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3618//
3619// Recursively walk the nodes. The nodes form a tree whose leaves are
3620// regular constants, which themselves are trees that createSpvConstant()
3621// recursively walks. So, this function walks the "top" of the tree:
3622// - emit specialization constant-building instructions for specConstant
3623// - when running into a non-spec-constant, switch to createSpvConstant()
3624spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3625{
3626 assert(node.getQualifier().storage == glslang::EvqConst);
3627
John Kessenich6c292d32016-02-15 20:58:50 -07003628 if (! node.getQualifier().specConstant) {
3629 // hand off to the non-spec-constant path
3630 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3631 int nextConst = 0;
3632 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3633 nextConst, false);
3634 }
3635
3636 // We now know we have a specialization constant to build
3637
3638 if (node.getAsSymbolNode() && node.getQualifier().hasSpecConstantId()) {
3639 // this is a direct literal assigned to a layout(constant_id=) declaration
3640 int nextConst = 0;
3641 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3642 nextConst, true);
3643 } else {
3644 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3645 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3646 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3647 std::vector<spv::Id> dimConstId;
3648 for (int dim = 0; dim < 3; ++dim) {
3649 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3650 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3651 if (specConst)
3652 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3653 }
3654 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3655 } else {
3656 spv::MissingFunctionality("specialization-constant expression trees");
3657 return spv::NoResult;
3658 }
3659 }
John Kessenich55e7d112015-11-15 21:33:39 -07003660}
3661
John Kessenich140f3df2015-06-26 16:58:36 -06003662// Use 'consts' as the flattened glslang source of scalar constants to recursively
3663// build the aggregate SPIR-V constant.
3664//
3665// If there are not enough elements present in 'consts', 0 will be substituted;
3666// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3667//
John Kessenich55e7d112015-11-15 21:33:39 -07003668spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003669{
3670 // vector of constants for SPIR-V
3671 std::vector<spv::Id> spvConsts;
3672
3673 // Type is used for struct and array constants
3674 spv::Id typeId = convertGlslangToSpvType(glslangType);
3675
3676 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003677 glslang::TType elementType(glslangType, 0);
3678 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003679 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003680 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003681 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003682 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003683 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003684 } else if (glslangType.getStruct()) {
3685 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3686 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003687 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003688 } else if (glslangType.isVector()) {
3689 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3690 bool zero = nextConst >= consts.size();
3691 switch (glslangType.getBasicType()) {
3692 case glslang::EbtInt:
3693 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3694 break;
3695 case glslang::EbtUint:
3696 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3697 break;
3698 case glslang::EbtFloat:
3699 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3700 break;
3701 case glslang::EbtDouble:
3702 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3703 break;
3704 case glslang::EbtBool:
3705 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3706 break;
3707 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003708 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003709 break;
3710 }
3711 ++nextConst;
3712 }
3713 } else {
3714 // we have a non-aggregate (scalar) constant
3715 bool zero = nextConst >= consts.size();
3716 spv::Id scalar = 0;
3717 switch (glslangType.getBasicType()) {
3718 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003719 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003720 break;
3721 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003722 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003723 break;
3724 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003725 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003726 break;
3727 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003728 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003729 break;
3730 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003731 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003732 break;
3733 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003734 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003735 break;
3736 }
3737 ++nextConst;
3738 return scalar;
3739 }
3740
3741 return builder.makeCompositeConstant(typeId, spvConsts);
3742}
3743
John Kessenich7c1aa102015-10-15 13:29:11 -06003744// Return true if the node is a constant or symbol whose reading has no
3745// non-trivial observable cost or effect.
3746bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3747{
3748 // don't know what this is
3749 if (node == nullptr)
3750 return false;
3751
3752 // a constant is safe
3753 if (node->getAsConstantUnion() != nullptr)
3754 return true;
3755
3756 // not a symbol means non-trivial
3757 if (node->getAsSymbolNode() == nullptr)
3758 return false;
3759
3760 // a symbol, depends on what's being read
3761 switch (node->getType().getQualifier().storage) {
3762 case glslang::EvqTemporary:
3763 case glslang::EvqGlobal:
3764 case glslang::EvqIn:
3765 case glslang::EvqInOut:
3766 case glslang::EvqConst:
3767 case glslang::EvqConstReadOnly:
3768 case glslang::EvqUniform:
3769 return true;
3770 default:
3771 return false;
3772 }
3773}
3774
3775// A node is trivial if it is a single operation with no side effects.
3776// Error on the side of saying non-trivial.
3777// Return true if trivial.
3778bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3779{
3780 if (node == nullptr)
3781 return false;
3782
3783 // symbols and constants are trivial
3784 if (isTrivialLeaf(node))
3785 return true;
3786
3787 // otherwise, it needs to be a simple operation or one or two leaf nodes
3788
3789 // not a simple operation
3790 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3791 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3792 if (binaryNode == nullptr && unaryNode == nullptr)
3793 return false;
3794
3795 // not on leaf nodes
3796 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3797 return false;
3798
3799 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3800 return false;
3801 }
3802
3803 switch (node->getAsOperator()->getOp()) {
3804 case glslang::EOpLogicalNot:
3805 case glslang::EOpConvIntToBool:
3806 case glslang::EOpConvUintToBool:
3807 case glslang::EOpConvFloatToBool:
3808 case glslang::EOpConvDoubleToBool:
3809 case glslang::EOpEqual:
3810 case glslang::EOpNotEqual:
3811 case glslang::EOpLessThan:
3812 case glslang::EOpGreaterThan:
3813 case glslang::EOpLessThanEqual:
3814 case glslang::EOpGreaterThanEqual:
3815 case glslang::EOpIndexDirect:
3816 case glslang::EOpIndexDirectStruct:
3817 case glslang::EOpLogicalXor:
3818 case glslang::EOpAny:
3819 case glslang::EOpAll:
3820 return true;
3821 default:
3822 return false;
3823 }
3824}
3825
3826// Emit short-circuiting code, where 'right' is never evaluated unless
3827// the left side is true (for &&) or false (for ||).
3828spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3829{
3830 spv::Id boolTypeId = builder.makeBoolType();
3831
3832 // emit left operand
3833 builder.clearAccessChain();
3834 left.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003835 spv::Id leftId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003836
3837 // Operands to accumulate OpPhi operands
3838 std::vector<spv::Id> phiOperands;
3839 // accumulate left operand's phi information
3840 phiOperands.push_back(leftId);
3841 phiOperands.push_back(builder.getBuildPoint()->getId());
3842
3843 // Make the two kinds of operation symmetric with a "!"
3844 // || => emit "if (! left) result = right"
3845 // && => emit "if ( left) result = right"
3846 //
3847 // TODO: this runtime "not" for || could be avoided by adding functionality
3848 // to 'builder' to have an "else" without an "then"
3849 if (op == glslang::EOpLogicalOr)
3850 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3851
3852 // make an "if" based on the left value
3853 spv::Builder::If ifBuilder(leftId, builder);
3854
3855 // emit right operand as the "then" part of the "if"
3856 builder.clearAccessChain();
3857 right.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003858 spv::Id rightId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003859
3860 // accumulate left operand's phi information
3861 phiOperands.push_back(rightId);
3862 phiOperands.push_back(builder.getBuildPoint()->getId());
3863
3864 // finish the "if"
3865 ifBuilder.makeEndIf();
3866
3867 // phi together the two results
3868 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3869}
3870
John Kessenich140f3df2015-06-26 16:58:36 -06003871}; // end anonymous namespace
3872
3873namespace glslang {
3874
John Kessenich68d78fd2015-07-12 19:28:10 -06003875void GetSpirvVersion(std::string& version)
3876{
John Kessenich9e55f632015-07-15 10:03:39 -06003877 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003878 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003879 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003880 version = buf;
3881}
3882
John Kessenich140f3df2015-06-26 16:58:36 -06003883// Write SPIR-V out to a binary file
3884void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3885{
3886 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003887 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003888 for (int i = 0; i < (int)spirv.size(); ++i) {
3889 unsigned int word = spirv[i];
3890 out.write((const char*)&word, 4);
3891 }
3892 out.close();
3893}
3894
3895//
3896// Set up the glslang traversal
3897//
3898void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3899{
3900 TIntermNode* root = intermediate.getTreeRoot();
3901
3902 if (root == 0)
3903 return;
3904
3905 glslang::GetThreadPoolAllocator().push();
3906
3907 TGlslangToSpvTraverser it(&intermediate);
3908
3909 root->traverse(&it);
3910
3911 it.dumpSpv(spirv);
3912
3913 glslang::GetThreadPoolAllocator().pop();
3914}
3915
3916}; // end namespace glslang