blob: 5eb097bd7ac024a2f2703209ed327df61718b93f [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);
Rex Xu27253232016-02-23 17:51:09 +0800101 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700102 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700103 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
104 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
105 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 -0600106
107 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
108 void makeFunctions(const glslang::TIntermSequence&);
109 void makeGlobalInitializers(const glslang::TIntermSequence&);
110 void visitFunctions(const glslang::TIntermSequence&);
111 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800112 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600113 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
114 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600115 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
116
117 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 -0700118 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800119 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 -0700120 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600121 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
122 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800123 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 -0600124 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 -0600125 spv::Id createNoArgOperation(glslang::TOperator op);
126 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
127 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700128 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600129 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700130 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
John Kessenich55e7d112015-11-15 21:33:39 -0700131 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
132 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600133 bool isTrivialLeaf(const glslang::TIntermTyped* node);
134 bool isTrivial(const glslang::TIntermTyped* node);
135 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600136
137 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700138 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600139 int sequenceDepth;
140
141 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
142 spv::Builder builder;
143 bool inMain;
144 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700145 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 -0700146 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600147 const glslang::TIntermediate* glslangIntermediate;
148 spv::Id stdBuiltins;
149
John Kessenich2f273362015-07-18 22:34:27 -0600150 std::unordered_map<int, spv::Id> symbolValues;
151 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
152 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700153 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600154 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 -0600155 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600156};
157
158//
159// Helper functions for translating glslang representations to SPIR-V enumerants.
160//
161
162// Translate glslang profile to SPIR-V source language.
163spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
164{
165 switch (profile) {
166 case ENoProfile:
167 case ECoreProfile:
168 case ECompatibilityProfile:
169 return spv::SourceLanguageGLSL;
170 case EEsProfile:
171 return spv::SourceLanguageESSL;
172 default:
173 return spv::SourceLanguageUnknown;
174 }
175}
176
177// Translate glslang language (stage) to SPIR-V execution model.
178spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
179{
180 switch (stage) {
181 case EShLangVertex: return spv::ExecutionModelVertex;
182 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
183 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
184 case EShLangGeometry: return spv::ExecutionModelGeometry;
185 case EShLangFragment: return spv::ExecutionModelFragment;
186 case EShLangCompute: return spv::ExecutionModelGLCompute;
187 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700188 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600189 return spv::ExecutionModelFragment;
190 }
191}
192
193// Translate glslang type to SPIR-V storage class.
194spv::StorageClass TranslateStorageClass(const glslang::TType& type)
195{
196 if (type.getQualifier().isPipeInput())
197 return spv::StorageClassInput;
198 else if (type.getQualifier().isPipeOutput())
199 return spv::StorageClassOutput;
200 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700201 if (type.getQualifier().layoutPushConstant)
202 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600203 if (type.getBasicType() == glslang::EbtBlock)
204 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800205 else if (type.getBasicType() == glslang::EbtAtomicUint)
206 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600207 else
208 return spv::StorageClassUniformConstant;
209 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
210 } else {
211 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700212 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
213 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600214 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
215 case glslang::EvqTemporary: return spv::StorageClassFunction;
216 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700217 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600218 return spv::StorageClassFunction;
219 }
220 }
221}
222
223// Translate glslang sampler type to SPIR-V dimensionality.
224spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
225{
226 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700227 case glslang::Esd1D: return spv::Dim1D;
228 case glslang::Esd2D: return spv::Dim2D;
229 case glslang::Esd3D: return spv::Dim3D;
230 case glslang::EsdCube: return spv::DimCube;
231 case glslang::EsdRect: return spv::DimRect;
232 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700233 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600234 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700235 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600236 return spv::Dim2D;
237 }
238}
239
240// Translate glslang type to SPIR-V precision decorations.
241spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
242{
243 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700244 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600245 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600246 default:
247 return spv::NoPrecision;
248 }
249}
250
251// Translate glslang type to SPIR-V block decorations.
252spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
253{
254 if (type.getBasicType() == glslang::EbtBlock) {
255 switch (type.getQualifier().storage) {
256 case glslang::EvqUniform: return spv::DecorationBlock;
257 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
258 case glslang::EvqVaryingIn: return spv::DecorationBlock;
259 case glslang::EvqVaryingOut: return spv::DecorationBlock;
260 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700261 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600262 break;
263 }
264 }
265
266 return (spv::Decoration)spv::BadValue;
267}
268
269// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700270spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600271{
272 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700273 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600274 case glslang::ElmRowMajor:
275 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700276 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600277 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700278 default:
279 // opaque layouts don't need a majorness
280 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600281 }
282 } else {
283 switch (type.getBasicType()) {
284 default:
285 return (spv::Decoration)spv::BadValue;
286 break;
287 case glslang::EbtBlock:
288 switch (type.getQualifier().storage) {
289 case glslang::EvqUniform:
290 case glslang::EvqBuffer:
291 switch (type.getQualifier().layoutPacking) {
292 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600293 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
294 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600295 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600296 }
297 case glslang::EvqVaryingIn:
298 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700299 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600300 return (spv::Decoration)spv::BadValue;
301 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700302 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600303 return (spv::Decoration)spv::BadValue;
304 }
305 }
306 }
307}
308
309// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700310// Returns spv::Decoration(spv::BadValue) when no decoration
311// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700312spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600313{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700314 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700315 // Smooth decoration doesn't exist in SPIR-V 1.0
316 return (spv::Decoration)spv::BadValue;
317 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700318 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700319 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700320 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600321 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700322 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600323 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700324 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600325 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700326 else if (qualifier.sample) {
327 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600328 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700329 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600330 return (spv::Decoration)spv::BadValue;
331}
332
John Kessenich92187592016-02-01 13:45:25 -0700333// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700334spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600335{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700336 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600337 return spv::DecorationInvariant;
338 else
339 return (spv::Decoration)spv::BadValue;
340}
341
342// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700343spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600344{
345 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700346 case glslang::EbvPointSize:
347 switch (glslangIntermediate->getStage()) {
348 case EShLangGeometry:
349 builder.addCapability(spv::CapabilityGeometryPointSize);
350 break;
351 case EShLangTessControl:
352 case EShLangTessEvaluation:
353 builder.addCapability(spv::CapabilityTessellationPointSize);
354 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100355 default:
356 break;
John Kessenich92187592016-02-01 13:45:25 -0700357 }
358 return spv::BuiltInPointSize;
359
360 case glslang::EbvClipDistance:
361 builder.addCapability(spv::CapabilityClipDistance);
362 return spv::BuiltInClipDistance;
363
364 case glslang::EbvCullDistance:
365 builder.addCapability(spv::CapabilityCullDistance);
366 return spv::BuiltInCullDistance;
367
368 case glslang::EbvViewportIndex:
369 // TODO: builder.addCapability(spv::CapabilityMultiViewport);
370 return spv::BuiltInViewportIndex;
371
John Kessenich5e801132016-02-15 11:09:46 -0700372 case glslang::EbvSampleId:
373 builder.addCapability(spv::CapabilitySampleRateShading);
374 return spv::BuiltInSampleId;
375
376 case glslang::EbvSamplePosition:
377 builder.addCapability(spv::CapabilitySampleRateShading);
378 return spv::BuiltInSamplePosition;
379
380 case glslang::EbvSampleMask:
381 builder.addCapability(spv::CapabilitySampleRateShading);
382 return spv::BuiltInSampleMask;
383
John Kessenich140f3df2015-06-26 16:58:36 -0600384 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600385 case glslang::EbvVertexId: return spv::BuiltInVertexId;
386 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700387 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
388 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600389 case glslang::EbvBaseVertex:
390 case glslang::EbvBaseInstance:
391 case glslang::EbvDrawId:
392 // TODO: Add SPIR-V builtin ID.
393 spv::MissingFunctionality("Draw parameters");
394 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600395 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
396 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
397 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600398 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
399 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
400 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
401 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
402 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
403 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
404 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600405 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
406 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
407 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
408 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
409 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
410 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
411 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
412 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
413 default: return (spv::BuiltIn)spv::BadValue;
414 }
415}
416
Rex Xufc618912015-09-09 16:42:49 +0800417// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700418spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800419{
420 assert(type.getBasicType() == glslang::EbtSampler);
421
John Kessenich5d0fa972016-02-15 11:57:00 -0700422 // Check for capabilities
423 switch (type.getQualifier().layoutFormat) {
424 case glslang::ElfRg32f:
425 case glslang::ElfRg16f:
426 case glslang::ElfR11fG11fB10f:
427 case glslang::ElfR16f:
428 case glslang::ElfRgba16:
429 case glslang::ElfRgb10A2:
430 case glslang::ElfRg16:
431 case glslang::ElfRg8:
432 case glslang::ElfR16:
433 case glslang::ElfR8:
434 case glslang::ElfRgba16Snorm:
435 case glslang::ElfRg16Snorm:
436 case glslang::ElfRg8Snorm:
437 case glslang::ElfR16Snorm:
438 case glslang::ElfR8Snorm:
439
440 case glslang::ElfRg32i:
441 case glslang::ElfRg16i:
442 case glslang::ElfRg8i:
443 case glslang::ElfR16i:
444 case glslang::ElfR8i:
445
446 case glslang::ElfRgb10a2ui:
447 case glslang::ElfRg32ui:
448 case glslang::ElfRg16ui:
449 case glslang::ElfRg8ui:
450 case glslang::ElfR16ui:
451 case glslang::ElfR8ui:
452 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
453 break;
454
455 default:
456 break;
457 }
458
459 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800460 switch (type.getQualifier().layoutFormat) {
461 case glslang::ElfNone: return spv::ImageFormatUnknown;
462 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
463 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
464 case glslang::ElfR32f: return spv::ImageFormatR32f;
465 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
466 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
467 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
468 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
469 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
470 case glslang::ElfR16f: return spv::ImageFormatR16f;
471 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
472 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
473 case glslang::ElfRg16: return spv::ImageFormatRg16;
474 case glslang::ElfRg8: return spv::ImageFormatRg8;
475 case glslang::ElfR16: return spv::ImageFormatR16;
476 case glslang::ElfR8: return spv::ImageFormatR8;
477 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
478 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
479 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
480 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
481 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
482 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
483 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
484 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
485 case glslang::ElfR32i: return spv::ImageFormatR32i;
486 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
487 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
488 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
489 case glslang::ElfR16i: return spv::ImageFormatR16i;
490 case glslang::ElfR8i: return spv::ImageFormatR8i;
491 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
492 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
493 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
494 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
495 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
496 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
497 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
498 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
499 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
500 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
501 default: return (spv::ImageFormat)spv::BadValue;
502 }
503}
504
John Kessenich6c292d32016-02-15 20:58:50 -0700505// Return whether or not the given type is something that should be tied to a
506// descriptor set.
507bool IsDescriptorResource(const glslang::TType& type)
508{
509 // uniform and buffer blocks are included
510 if (type.getBasicType() == glslang::EbtBlock)
511 return type.getQualifier().isUniformOrBuffer();
512
513 // non block...
514 // basically samplerXXX/subpass/sampler/texture are all included
515 // if they are the global-scope-class, not the function parameter
516 // (or local, if they ever exist) class.
517 if (type.getBasicType() == glslang::EbtSampler)
518 return type.getQualifier().isUniformOrBuffer();
519
520 // None of the above.
521 return false;
522}
523
John Kesseniche0b6cad2015-12-24 10:30:13 -0700524void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
525{
526 if (child.layoutMatrix == glslang::ElmNone)
527 child.layoutMatrix = parent.layoutMatrix;
528
529 if (parent.invariant)
530 child.invariant = true;
531 if (parent.nopersp)
532 child.nopersp = true;
533 if (parent.flat)
534 child.flat = true;
535 if (parent.centroid)
536 child.centroid = true;
537 if (parent.patch)
538 child.patch = true;
539 if (parent.sample)
540 child.sample = true;
541}
542
543bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
544{
John Kessenich7b9fa252016-01-21 18:56:57 -0700545 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700546 // - struct members can inherit from a struct declaration
547 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
548 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700549 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700550}
551
John Kessenich140f3df2015-06-26 16:58:36 -0600552//
553// Implement the TGlslangToSpvTraverser class.
554//
555
556TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
557 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700558 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600559 inMain(false), mainTerminated(false), linkageOnly(false),
560 glslangIntermediate(glslangIntermediate)
561{
562 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
563
564 builder.clearAccessChain();
565 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
566 stdBuiltins = builder.import("GLSL.std.450");
567 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
568 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700569 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600570
571 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600572 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
573 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600574 builder.addSourceExtension(it->c_str());
575
576 // Add the top-level modes for this shader.
577
John Kessenich92187592016-02-01 13:45:25 -0700578 if (glslangIntermediate->getXfbMode()) {
579 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600580 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700581 }
John Kessenich140f3df2015-06-26 16:58:36 -0600582
583 unsigned int mode;
584 switch (glslangIntermediate->getStage()) {
585 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600586 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600587 break;
588
589 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600590 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600591 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
592 break;
593
594 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600595 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600596 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700597 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
598 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
599 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600600 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600601 }
602 if (mode != spv::BadValue)
603 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
604
John Kesseniche6903322015-10-13 16:29:02 -0600605 switch (glslangIntermediate->getVertexSpacing()) {
606 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
607 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
608 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
609 default: mode = spv::BadValue; break;
610 }
611 if (mode != spv::BadValue)
612 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
613
614 switch (glslangIntermediate->getVertexOrder()) {
615 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
616 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
617 default: mode = spv::BadValue; break;
618 }
619 if (mode != spv::BadValue)
620 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
621
622 if (glslangIntermediate->getPointMode())
623 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600624 break;
625
626 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600627 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600628 switch (glslangIntermediate->getInputPrimitive()) {
629 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
630 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
631 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700632 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600633 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
634 default: mode = spv::BadValue; break;
635 }
636 if (mode != spv::BadValue)
637 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600638
John Kessenich140f3df2015-06-26 16:58:36 -0600639 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
640
641 switch (glslangIntermediate->getOutputPrimitive()) {
642 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
643 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
644 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
645 default: mode = spv::BadValue; break;
646 }
647 if (mode != spv::BadValue)
648 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
649 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
650 break;
651
652 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600653 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600654 if (glslangIntermediate->getPixelCenterInteger())
655 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600656
John Kessenich140f3df2015-06-26 16:58:36 -0600657 if (glslangIntermediate->getOriginUpperLeft())
658 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600659 else
660 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600661
662 if (glslangIntermediate->getEarlyFragmentTests())
663 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
664
665 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600666 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
667 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
668 default: mode = spv::BadValue; break;
669 }
670 if (mode != spv::BadValue)
671 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
672
673 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
674 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600675 break;
676
677 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600678 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600679 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
680 glslangIntermediate->getLocalSize(1),
681 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600682 break;
683
684 default:
685 break;
686 }
687
688}
689
John Kessenich7ba63412015-12-20 17:37:07 -0700690// Finish everything and dump
691void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
692{
693 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100694 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
695 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700696
697 builder.dump(out);
698}
699
John Kessenich140f3df2015-06-26 16:58:36 -0600700TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
701{
702 if (! mainTerminated) {
703 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
704 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600705 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600706 }
707}
708
709//
710// Implement the traversal functions.
711//
712// Return true from interior nodes to have the external traversal
713// continue on to children. Return false if children were
714// already processed.
715//
716
717//
718// Symbols can turn into
719// - uniform/input reads
720// - output writes
721// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
722// - something simple that degenerates into the last bullet
723//
724void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
725{
726 // getSymbolId() will set up all the IO decorations on the first call.
727 // Formal function parameters were mapped during makeFunctions().
728 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700729
730 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
731 if (builder.isPointer(id)) {
732 spv::StorageClass sc = builder.getStorageClass(id);
733 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
734 iOSet.insert(id);
735 }
736
737 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700738 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600739 // Prepare to generate code for the access
740
741 // L-value chains will be computed left to right. We're on the symbol now,
742 // which is the left-most part of the access chain, so now is "clear" time,
743 // followed by setting the base.
744 builder.clearAccessChain();
745
746 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700747 // except for
748 // A) "const in" arguments to a function, which are an intermediate object.
749 // See comments in handleUserFunctionCall().
750 // B) Specialization constants (normal constant don't even come in as a variable),
751 // These are also pure R-values.
752 glslang::TQualifier qualifier = symbol->getQualifier();
753 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
754 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600755 builder.setAccessChainRValue(id);
756 else
757 builder.setAccessChainLValue(id);
758 }
759}
760
761bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
762{
763 // First, handle special cases
764 switch (node->getOp()) {
765 case glslang::EOpAssign:
766 case glslang::EOpAddAssign:
767 case glslang::EOpSubAssign:
768 case glslang::EOpMulAssign:
769 case glslang::EOpVectorTimesMatrixAssign:
770 case glslang::EOpVectorTimesScalarAssign:
771 case glslang::EOpMatrixTimesScalarAssign:
772 case glslang::EOpMatrixTimesMatrixAssign:
773 case glslang::EOpDivAssign:
774 case glslang::EOpModAssign:
775 case glslang::EOpAndAssign:
776 case glslang::EOpInclusiveOrAssign:
777 case glslang::EOpExclusiveOrAssign:
778 case glslang::EOpLeftShiftAssign:
779 case glslang::EOpRightShiftAssign:
780 // A bin-op assign "a += b" means the same thing as "a = a + b"
781 // where a is evaluated before b. For a simple assignment, GLSL
782 // says to evaluate the left before the right. So, always, left
783 // node then right node.
784 {
785 // get the left l-value, save it away
786 builder.clearAccessChain();
787 node->getLeft()->traverse(this);
788 spv::Builder::AccessChain lValue = builder.getAccessChain();
789
790 // evaluate the right
791 builder.clearAccessChain();
792 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700793 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600794
795 if (node->getOp() != glslang::EOpAssign) {
796 // the left is also an r-value
797 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700798 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600799
800 // do the operation
801 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
802 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
803 node->getType().getBasicType());
804
805 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700806 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600807 }
808
809 // store the result
810 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800811 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600812
813 // assignments are expressions having an rValue after they are evaluated...
814 builder.clearAccessChain();
815 builder.setAccessChainRValue(rValue);
816 }
817 return false;
818 case glslang::EOpIndexDirect:
819 case glslang::EOpIndexDirectStruct:
820 {
821 // Get the left part of the access chain.
822 node->getLeft()->traverse(this);
823
824 // Add the next element in the chain
825
John Kessenich55e7d112015-11-15 21:33:39 -0700826 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600827 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
828 // This may be, e.g., an anonymous block-member selection, which generally need
829 // index remapping due to hidden members in anonymous blocks.
830 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700831 assert(remapper.size() > 0);
832 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600833 }
834
835 if (! node->getLeft()->getType().isArray() &&
836 node->getLeft()->getType().isVector() &&
837 node->getOp() == glslang::EOpIndexDirect) {
838 // This is essentially a hard-coded vector swizzle of size 1,
839 // so short circuit the access-chain stuff with a swizzle.
840 std::vector<unsigned> swizzle;
841 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600842 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600843 } else {
844 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600845 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600846 }
847 }
848 return false;
849 case glslang::EOpIndexIndirect:
850 {
851 // Structure or array or vector indirection.
852 // Will use native SPIR-V access-chain for struct and array indirection;
853 // matrices are arrays of vectors, so will also work for a matrix.
854 // Will use the access chain's 'component' for variable index into a vector.
855
856 // This adapter is building access chains left to right.
857 // Set up the access chain to the left.
858 node->getLeft()->traverse(this);
859
860 // save it so that computing the right side doesn't trash it
861 spv::Builder::AccessChain partial = builder.getAccessChain();
862
863 // compute the next index in the chain
864 builder.clearAccessChain();
865 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700866 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600867
868 // restore the saved access chain
869 builder.setAccessChain(partial);
870
871 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600872 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600873 else
John Kessenichfa668da2015-09-13 14:46:30 -0600874 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600875 }
876 return false;
877 case glslang::EOpVectorSwizzle:
878 {
879 node->getLeft()->traverse(this);
880 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
881 std::vector<unsigned> swizzle;
882 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
883 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600884 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600885 }
886 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600887 case glslang::EOpLogicalOr:
888 case glslang::EOpLogicalAnd:
889 {
890
891 // These may require short circuiting, but can sometimes be done as straight
892 // binary operations. The right operand must be short circuited if it has
893 // side effects, and should probably be if it is complex.
894 if (isTrivial(node->getRight()->getAsTyped()))
895 break; // handle below as a normal binary operation
896 // otherwise, we need to do dynamic short circuiting on the right operand
897 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
898 builder.clearAccessChain();
899 builder.setAccessChainRValue(result);
900 }
901 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600902 default:
903 break;
904 }
905
906 // Assume generic binary op...
907
John Kessenich32cfd492016-02-02 12:37:46 -0700908 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600909 builder.clearAccessChain();
910 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700911 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600912
John Kessenich32cfd492016-02-02 12:37:46 -0700913 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600914 builder.clearAccessChain();
915 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700916 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600917
John Kessenich32cfd492016-02-02 12:37:46 -0700918 // get result
919 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
920 convertGlslangToSpvType(node->getType()), left, right,
921 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600922
John Kessenich50e57562015-12-21 21:21:11 -0700923 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600924 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700925 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700926 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600927 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600928 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600929 return false;
930 }
John Kessenich140f3df2015-06-26 16:58:36 -0600931}
932
933bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
934{
John Kessenichfc51d282015-08-19 13:34:18 -0600935 spv::Id result = spv::NoResult;
936
937 // try texturing first
938 result = createImageTextureFunctionCall(node);
939 if (result != spv::NoResult) {
940 builder.clearAccessChain();
941 builder.setAccessChainRValue(result);
942
943 return false; // done with this node
944 }
945
946 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600947
948 if (node->getOp() == glslang::EOpArrayLength) {
949 // Quite special; won't want to evaluate the operand.
950
951 // Normal .length() would have been constant folded by the front-end.
952 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600953 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600954 assert(node->getOperand()->getType().isRuntimeSizedArray());
955 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
956 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600957 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
958 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600959
960 builder.clearAccessChain();
961 builder.setAccessChainRValue(length);
962
963 return false;
964 }
965
John Kessenichfc51d282015-08-19 13:34:18 -0600966 // Start by evaluating the operand
967
John Kessenich140f3df2015-06-26 16:58:36 -0600968 builder.clearAccessChain();
969 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800970
Rex Xufc618912015-09-09 16:42:49 +0800971 spv::Id operand = spv::NoResult;
972
973 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
974 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800975 node->getOp() == glslang::EOpAtomicCounter ||
976 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800977 operand = builder.accessChainGetLValue(); // Special case l-value operands
978 else
John Kessenich32cfd492016-02-02 12:37:46 -0700979 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600980
981 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
982
983 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600984 if (! result)
985 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600986
987 // if not, then possibly an operation
988 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700989 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600990
991 if (result) {
992 builder.clearAccessChain();
993 builder.setAccessChainRValue(result);
994
995 return false; // done with this node
996 }
997
998 // it must be a special case, check...
999 switch (node->getOp()) {
1000 case glslang::EOpPostIncrement:
1001 case glslang::EOpPostDecrement:
1002 case glslang::EOpPreIncrement:
1003 case glslang::EOpPreDecrement:
1004 {
1005 // we need the integer value "1" or the floating point "1.0" to add/subtract
1006 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
1007 builder.makeFloatConstant(1.0F) :
1008 builder.makeIntConstant(1);
1009 glslang::TOperator op;
1010 if (node->getOp() == glslang::EOpPreIncrement ||
1011 node->getOp() == glslang::EOpPostIncrement)
1012 op = glslang::EOpAdd;
1013 else
1014 op = glslang::EOpSub;
1015
1016 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1017 convertGlslangToSpvType(node->getType()), operand, one,
1018 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001019 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001020
1021 // The result of operation is always stored, but conditionally the
1022 // consumed result. The consumed result is always an r-value.
1023 builder.accessChainStore(result);
1024 builder.clearAccessChain();
1025 if (node->getOp() == glslang::EOpPreIncrement ||
1026 node->getOp() == glslang::EOpPreDecrement)
1027 builder.setAccessChainRValue(result);
1028 else
1029 builder.setAccessChainRValue(operand);
1030 }
1031
1032 return false;
1033
1034 case glslang::EOpEmitStreamVertex:
1035 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1036 return false;
1037 case glslang::EOpEndStreamPrimitive:
1038 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1039 return false;
1040
1041 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001042 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001043 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001044 }
John Kessenich140f3df2015-06-26 16:58:36 -06001045}
1046
1047bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1048{
John Kessenichfc51d282015-08-19 13:34:18 -06001049 spv::Id result = spv::NoResult;
1050
1051 // try texturing
1052 result = createImageTextureFunctionCall(node);
1053 if (result != spv::NoResult) {
1054 builder.clearAccessChain();
1055 builder.setAccessChainRValue(result);
1056
1057 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001058 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001059 // "imageStore" is a special case, which has no result
1060 return false;
1061 }
John Kessenichfc51d282015-08-19 13:34:18 -06001062
John Kessenich140f3df2015-06-26 16:58:36 -06001063 glslang::TOperator binOp = glslang::EOpNull;
1064 bool reduceComparison = true;
1065 bool isMatrix = false;
1066 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001067 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001068
1069 assert(node->getOp());
1070
1071 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1072
1073 switch (node->getOp()) {
1074 case glslang::EOpSequence:
1075 {
1076 if (preVisit)
1077 ++sequenceDepth;
1078 else
1079 --sequenceDepth;
1080
1081 if (sequenceDepth == 1) {
1082 // If this is the parent node of all the functions, we want to see them
1083 // early, so all call points have actual SPIR-V functions to reference.
1084 // In all cases, still let the traverser visit the children for us.
1085 makeFunctions(node->getAsAggregate()->getSequence());
1086
1087 // Also, we want all globals initializers to go into the entry of main(), before
1088 // anything else gets there, so visit out of order, doing them all now.
1089 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1090
1091 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1092 // so do them manually.
1093 visitFunctions(node->getAsAggregate()->getSequence());
1094
1095 return false;
1096 }
1097
1098 return true;
1099 }
1100 case glslang::EOpLinkerObjects:
1101 {
1102 if (visit == glslang::EvPreVisit)
1103 linkageOnly = true;
1104 else
1105 linkageOnly = false;
1106
1107 return true;
1108 }
1109 case glslang::EOpComma:
1110 {
1111 // processing from left to right naturally leaves the right-most
1112 // lying around in the access chain
1113 glslang::TIntermSequence& glslangOperands = node->getSequence();
1114 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1115 glslangOperands[i]->traverse(this);
1116
1117 return false;
1118 }
1119 case glslang::EOpFunction:
1120 if (visit == glslang::EvPreVisit) {
1121 if (isShaderEntrypoint(node)) {
1122 inMain = true;
1123 builder.setBuildPoint(shaderEntry->getLastBlock());
1124 } else {
1125 handleFunctionEntry(node);
1126 }
1127 } else {
1128 if (inMain)
1129 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001130 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001131 inMain = false;
1132 }
1133
1134 return true;
1135 case glslang::EOpParameters:
1136 // Parameters will have been consumed by EOpFunction processing, but not
1137 // the body, so we still visited the function node's children, making this
1138 // child redundant.
1139 return false;
1140 case glslang::EOpFunctionCall:
1141 {
1142 if (node->isUserDefined())
1143 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001144 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1145 if (result) {
1146 builder.clearAccessChain();
1147 builder.setAccessChainRValue(result);
1148 } else
1149 spv::MissingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001150
1151 return false;
1152 }
1153 case glslang::EOpConstructMat2x2:
1154 case glslang::EOpConstructMat2x3:
1155 case glslang::EOpConstructMat2x4:
1156 case glslang::EOpConstructMat3x2:
1157 case glslang::EOpConstructMat3x3:
1158 case glslang::EOpConstructMat3x4:
1159 case glslang::EOpConstructMat4x2:
1160 case glslang::EOpConstructMat4x3:
1161 case glslang::EOpConstructMat4x4:
1162 case glslang::EOpConstructDMat2x2:
1163 case glslang::EOpConstructDMat2x3:
1164 case glslang::EOpConstructDMat2x4:
1165 case glslang::EOpConstructDMat3x2:
1166 case glslang::EOpConstructDMat3x3:
1167 case glslang::EOpConstructDMat3x4:
1168 case glslang::EOpConstructDMat4x2:
1169 case glslang::EOpConstructDMat4x3:
1170 case glslang::EOpConstructDMat4x4:
1171 isMatrix = true;
1172 // fall through
1173 case glslang::EOpConstructFloat:
1174 case glslang::EOpConstructVec2:
1175 case glslang::EOpConstructVec3:
1176 case glslang::EOpConstructVec4:
1177 case glslang::EOpConstructDouble:
1178 case glslang::EOpConstructDVec2:
1179 case glslang::EOpConstructDVec3:
1180 case glslang::EOpConstructDVec4:
1181 case glslang::EOpConstructBool:
1182 case glslang::EOpConstructBVec2:
1183 case glslang::EOpConstructBVec3:
1184 case glslang::EOpConstructBVec4:
1185 case glslang::EOpConstructInt:
1186 case glslang::EOpConstructIVec2:
1187 case glslang::EOpConstructIVec3:
1188 case glslang::EOpConstructIVec4:
1189 case glslang::EOpConstructUint:
1190 case glslang::EOpConstructUVec2:
1191 case glslang::EOpConstructUVec3:
1192 case glslang::EOpConstructUVec4:
1193 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001194 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001195 {
1196 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001197 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001198 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1199 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001200 if (node->getOp() == glslang::EOpConstructTextureSampler)
1201 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1202 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001203 std::vector<spv::Id> constituents;
1204 for (int c = 0; c < (int)arguments.size(); ++c)
1205 constituents.push_back(arguments[c]);
1206 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001207 } else if (isMatrix)
1208 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1209 else
1210 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001211
1212 builder.clearAccessChain();
1213 builder.setAccessChainRValue(constructed);
1214
1215 return false;
1216 }
1217
1218 // These six are component-wise compares with component-wise results.
1219 // Forward on to createBinaryOperation(), requesting a vector result.
1220 case glslang::EOpLessThan:
1221 case glslang::EOpGreaterThan:
1222 case glslang::EOpLessThanEqual:
1223 case glslang::EOpGreaterThanEqual:
1224 case glslang::EOpVectorEqual:
1225 case glslang::EOpVectorNotEqual:
1226 {
1227 // Map the operation to a binary
1228 binOp = node->getOp();
1229 reduceComparison = false;
1230 switch (node->getOp()) {
1231 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1232 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1233 default: binOp = node->getOp(); break;
1234 }
1235
1236 break;
1237 }
1238 case glslang::EOpMul:
1239 // compontent-wise matrix multiply
1240 binOp = glslang::EOpMul;
1241 break;
1242 case glslang::EOpOuterProduct:
1243 // two vectors multiplied to make a matrix
1244 binOp = glslang::EOpOuterProduct;
1245 break;
1246 case glslang::EOpDot:
1247 {
1248 // for scalar dot product, use multiply
1249 glslang::TIntermSequence& glslangOperands = node->getSequence();
1250 if (! glslangOperands[0]->getAsTyped()->isVector())
1251 binOp = glslang::EOpMul;
1252 break;
1253 }
1254 case glslang::EOpMod:
1255 // when an aggregate, this is the floating-point mod built-in function,
1256 // which can be emitted by the one in createBinaryOperation()
1257 binOp = glslang::EOpMod;
1258 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001259 case glslang::EOpEmitVertex:
1260 case glslang::EOpEndPrimitive:
1261 case glslang::EOpBarrier:
1262 case glslang::EOpMemoryBarrier:
1263 case glslang::EOpMemoryBarrierAtomicCounter:
1264 case glslang::EOpMemoryBarrierBuffer:
1265 case glslang::EOpMemoryBarrierImage:
1266 case glslang::EOpMemoryBarrierShared:
1267 case glslang::EOpGroupMemoryBarrier:
1268 noReturnValue = true;
1269 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1270 break;
1271
John Kessenich426394d2015-07-23 10:22:48 -06001272 case glslang::EOpAtomicAdd:
1273 case glslang::EOpAtomicMin:
1274 case glslang::EOpAtomicMax:
1275 case glslang::EOpAtomicAnd:
1276 case glslang::EOpAtomicOr:
1277 case glslang::EOpAtomicXor:
1278 case glslang::EOpAtomicExchange:
1279 case glslang::EOpAtomicCompSwap:
1280 atomic = true;
1281 break;
1282
John Kessenich140f3df2015-06-26 16:58:36 -06001283 default:
1284 break;
1285 }
1286
1287 //
1288 // See if it maps to a regular operation.
1289 //
John Kessenich140f3df2015-06-26 16:58:36 -06001290 if (binOp != glslang::EOpNull) {
1291 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1292 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1293 assert(left && right);
1294
1295 builder.clearAccessChain();
1296 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001297 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001298
1299 builder.clearAccessChain();
1300 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001301 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001302
1303 result = createBinaryOperation(binOp, precision,
1304 convertGlslangToSpvType(node->getType()), leftId, rightId,
1305 left->getType().getBasicType(), reduceComparison);
1306
1307 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001308 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001309 builder.clearAccessChain();
1310 builder.setAccessChainRValue(result);
1311
1312 return false;
1313 }
1314
John Kessenich426394d2015-07-23 10:22:48 -06001315 //
1316 // Create the list of operands.
1317 //
John Kessenich140f3df2015-06-26 16:58:36 -06001318 glslang::TIntermSequence& glslangOperands = node->getSequence();
1319 std::vector<spv::Id> operands;
1320 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1321 builder.clearAccessChain();
1322 glslangOperands[arg]->traverse(this);
1323
1324 // special case l-value operands; there are just a few
1325 bool lvalue = false;
1326 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001327 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001328 case glslang::EOpModf:
1329 if (arg == 1)
1330 lvalue = true;
1331 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001332 case glslang::EOpInterpolateAtSample:
1333 case glslang::EOpInterpolateAtOffset:
1334 if (arg == 0)
1335 lvalue = true;
1336 break;
Rex Xud4782c12015-09-06 16:30:11 +08001337 case glslang::EOpAtomicAdd:
1338 case glslang::EOpAtomicMin:
1339 case glslang::EOpAtomicMax:
1340 case glslang::EOpAtomicAnd:
1341 case glslang::EOpAtomicOr:
1342 case glslang::EOpAtomicXor:
1343 case glslang::EOpAtomicExchange:
1344 case glslang::EOpAtomicCompSwap:
1345 if (arg == 0)
1346 lvalue = true;
1347 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001348 case glslang::EOpAddCarry:
1349 case glslang::EOpSubBorrow:
1350 if (arg == 2)
1351 lvalue = true;
1352 break;
1353 case glslang::EOpUMulExtended:
1354 case glslang::EOpIMulExtended:
1355 if (arg >= 2)
1356 lvalue = true;
1357 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001358 default:
1359 break;
1360 }
1361 if (lvalue)
1362 operands.push_back(builder.accessChainGetLValue());
1363 else
John Kessenich32cfd492016-02-02 12:37:46 -07001364 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001365 }
John Kessenich426394d2015-07-23 10:22:48 -06001366
1367 if (atomic) {
1368 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001369 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001370 } else {
1371 // Pass through to generic operations.
1372 switch (glslangOperands.size()) {
1373 case 0:
1374 result = createNoArgOperation(node->getOp());
1375 break;
1376 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001377 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001378 break;
1379 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001380 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001381 break;
1382 }
John Kessenich140f3df2015-06-26 16:58:36 -06001383 }
1384
1385 if (noReturnValue)
1386 return false;
1387
1388 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001389 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001390 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001391 } else {
1392 builder.clearAccessChain();
1393 builder.setAccessChainRValue(result);
1394 return false;
1395 }
1396}
1397
1398bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1399{
1400 // This path handles both if-then-else and ?:
1401 // The if-then-else has a node type of void, while
1402 // ?: has a non-void node type
1403 spv::Id result = 0;
1404 if (node->getBasicType() != glslang::EbtVoid) {
1405 // don't handle this as just on-the-fly temporaries, because there will be two names
1406 // and better to leave SSA to later passes
1407 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1408 }
1409
1410 // emit the condition before doing anything with selection
1411 node->getCondition()->traverse(this);
1412
1413 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001414 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001415
1416 if (node->getTrueBlock()) {
1417 // emit the "then" statement
1418 node->getTrueBlock()->traverse(this);
1419 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001420 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001421 }
1422
1423 if (node->getFalseBlock()) {
1424 ifBuilder.makeBeginElse();
1425 // emit the "else" statement
1426 node->getFalseBlock()->traverse(this);
1427 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001428 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001429 }
1430
1431 ifBuilder.makeEndIf();
1432
1433 if (result) {
1434 // GLSL only has r-values as the result of a :?, but
1435 // if we have an l-value, that can be more efficient if it will
1436 // become the base of a complex r-value expression, because the
1437 // next layer copies r-values into memory to use the access-chain mechanism
1438 builder.clearAccessChain();
1439 builder.setAccessChainLValue(result);
1440 }
1441
1442 return false;
1443}
1444
1445bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1446{
1447 // emit and get the condition before doing anything with switch
1448 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001449 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001450
1451 // browse the children to sort out code segments
1452 int defaultSegment = -1;
1453 std::vector<TIntermNode*> codeSegments;
1454 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1455 std::vector<int> caseValues;
1456 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1457 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1458 TIntermNode* child = *c;
1459 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001460 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001461 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001462 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001463 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1464 } else
1465 codeSegments.push_back(child);
1466 }
1467
1468 // handle the case where the last code segment is missing, due to no code
1469 // statements between the last case and the end of the switch statement
1470 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1471 (int)codeSegments.size() == defaultSegment)
1472 codeSegments.push_back(nullptr);
1473
1474 // make the switch statement
1475 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001476 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001477
1478 // emit all the code in the segments
1479 breakForLoop.push(false);
1480 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1481 builder.nextSwitchSegment(segmentBlocks, s);
1482 if (codeSegments[s])
1483 codeSegments[s]->traverse(this);
1484 else
1485 builder.addSwitchBreak();
1486 }
1487 breakForLoop.pop();
1488
1489 builder.endSwitch(segmentBlocks);
1490
1491 return false;
1492}
1493
1494void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1495{
1496 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001497 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001498
1499 builder.clearAccessChain();
1500 builder.setAccessChainRValue(constant);
1501}
1502
1503bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1504{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001505 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001506 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001507 // Spec requires back edges to target header blocks, and every header block
1508 // must dominate its merge block. Make a header block first to ensure these
1509 // conditions are met. By definition, it will contain OpLoopMerge, followed
1510 // by a block-ending branch. But we don't want to put any other body/test
1511 // instructions in it, since the body/test may have arbitrary instructions,
1512 // including merges of its own.
1513 builder.setBuildPoint(&blocks.head);
1514 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001515 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001516 spv::Block& test = builder.makeNewBlock();
1517 builder.createBranch(&test);
1518
1519 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001520 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001521 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001522 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001523 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1524
1525 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001526 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001527 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001528 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001529 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001530 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001531
1532 builder.setBuildPoint(&blocks.continue_target);
1533 if (node->getTerminal())
1534 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001535 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001536 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001537 builder.createBranch(&blocks.body);
1538
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001539 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001540 builder.setBuildPoint(&blocks.body);
1541 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001542 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001543 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001544 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001545
1546 builder.setBuildPoint(&blocks.continue_target);
1547 if (node->getTerminal())
1548 node->getTerminal()->traverse(this);
1549 if (node->getTest()) {
1550 node->getTest()->traverse(this);
1551 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001552 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001553 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001554 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001555 // TODO: unless there was a break/return/discard instruction
1556 // somewhere in the body, this is an infinite loop, so we should
1557 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001558 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001559 }
John Kessenich140f3df2015-06-26 16:58:36 -06001560 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001561 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001562 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001563 return false;
1564}
1565
1566bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1567{
1568 if (node->getExpression())
1569 node->getExpression()->traverse(this);
1570
1571 switch (node->getFlowOp()) {
1572 case glslang::EOpKill:
1573 builder.makeDiscard();
1574 break;
1575 case glslang::EOpBreak:
1576 if (breakForLoop.top())
1577 builder.createLoopExit();
1578 else
1579 builder.addSwitchBreak();
1580 break;
1581 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001582 builder.createLoopContinue();
1583 break;
1584 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001585 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001586 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001587 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001588 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001589
1590 builder.clearAccessChain();
1591 break;
1592
1593 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001594 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001595 break;
1596 }
1597
1598 return false;
1599}
1600
1601spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1602{
1603 // First, steer off constants, which are not SPIR-V variables, but
1604 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001605 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001606 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001607 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001608 }
1609
1610 // Now, handle actual variables
1611 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1612 spv::Id spvType = convertGlslangToSpvType(node->getType());
1613
1614 const char* name = node->getName().c_str();
1615 if (glslang::IsAnonymous(name))
1616 name = "";
1617
1618 return builder.createVariable(storageClass, spvType, name);
1619}
1620
1621// Return type Id of the sampled type.
1622spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1623{
1624 switch (sampler.type) {
1625 case glslang::EbtFloat: return builder.makeFloatType(32);
1626 case glslang::EbtInt: return builder.makeIntType(32);
1627 case glslang::EbtUint: return builder.makeUintType(32);
1628 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001629 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001630 return builder.makeFloatType(32);
1631 }
1632}
1633
John Kessenich3ac051e2015-12-20 11:29:16 -07001634// Convert from a glslang type to an SPV type, by calling into a
1635// recursive version of this function. This establishes the inherited
1636// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001637spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1638{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001639 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001640}
1641
1642// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001643// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001644spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001645{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001646 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001647
1648 switch (type.getBasicType()) {
1649 case glslang::EbtVoid:
1650 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001651 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001652 break;
1653 case glslang::EbtFloat:
1654 spvType = builder.makeFloatType(32);
1655 break;
1656 case glslang::EbtDouble:
1657 spvType = builder.makeFloatType(64);
1658 break;
1659 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001660 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1661 // a 32-bit int where non-0 means true.
1662 if (explicitLayout != glslang::ElpNone)
1663 spvType = builder.makeUintType(32);
1664 else
1665 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001666 break;
1667 case glslang::EbtInt:
1668 spvType = builder.makeIntType(32);
1669 break;
1670 case glslang::EbtUint:
1671 spvType = builder.makeUintType(32);
1672 break;
John Kessenich426394d2015-07-23 10:22:48 -06001673 case glslang::EbtAtomicUint:
1674 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1675 spvType = builder.makeUintType(32);
1676 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001677 case glslang::EbtSampler:
1678 {
1679 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001680 if (sampler.sampler) {
1681 // pure sampler
1682 spvType = builder.makeSamplerType();
1683 } else {
1684 // an image is present, make its type
1685 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1686 sampler.image ? 2 : 1, TranslateImageFormat(type));
1687 if (sampler.combined) {
1688 // already has both image and sampler, make the combined type
1689 spvType = builder.makeSampledImageType(spvType);
1690 }
John Kessenich55e7d112015-11-15 21:33:39 -07001691 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001692 }
John Kessenich140f3df2015-06-26 16:58:36 -06001693 break;
1694 case glslang::EbtStruct:
1695 case glslang::EbtBlock:
1696 {
1697 // If we've seen this struct type, return it
1698 const glslang::TTypeList* glslangStruct = type.getStruct();
1699 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001700
1701 // Try to share structs for different layouts, but not yet for other
1702 // kinds of qualification (primarily not yet including interpolant qualification).
1703 if (! HasNonLayoutQualifiers(qualifier))
1704 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1705 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001706 break;
1707
1708 // else, we haven't seen it...
1709
1710 // Create a vector of struct types for SPIR-V to consume
1711 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1712 if (type.getBasicType() == glslang::EbtBlock)
1713 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001714 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001715 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1716 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1717 if (glslangType.hiddenMember()) {
1718 ++memberDelta;
1719 if (type.getBasicType() == glslang::EbtBlock)
1720 memberRemapper[glslangStruct][i] = -1;
1721 } else {
1722 if (type.getBasicType() == glslang::EbtBlock)
1723 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001724 // modify just this child's view of the qualifier
1725 glslang::TQualifier subQualifier = glslangType.getQualifier();
1726 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001727
1728 // manually inherit location; it's more complex
1729 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1730 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1731 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001732 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001733
1734 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001735 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001736 }
1737 }
1738
1739 // Make the SPIR-V type
1740 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001741 if (! HasNonLayoutQualifiers(qualifier))
1742 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001743
1744 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001745 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001746 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001747 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1748 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1749 int member = i;
1750 if (type.getBasicType() == glslang::EbtBlock)
1751 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001752
John Kesseniche0b6cad2015-12-24 10:30:13 -07001753 // modify just this child's view of the qualifier
1754 glslang::TQualifier subQualifier = glslangType.getQualifier();
1755 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001756
John Kessenich140f3df2015-06-26 16:58:36 -06001757 // using -1 above to indicate a hidden member
1758 if (member >= 0) {
1759 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001760 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001761 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001762 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1763 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001764
1765 // compute location decoration; tricky based on whether inheritance is at play
1766 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1767 // probably move to the linker stage of the front end proper, and just have the
1768 // answer sitting already distributed throughout the individual member locations.
1769 int location = -1; // will only decorate if present or inherited
1770 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1771 location = subQualifier.layoutLocation;
1772 else if (qualifier.hasLocation()) // inheritance
1773 location = qualifier.layoutLocation + locationOffset;
1774 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001775 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001776 if (location >= 0)
1777 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1778
1779 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001780 if (glslangType.getQualifier().hasComponent())
1781 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1782 if (glslangType.getQualifier().hasXfbOffset())
1783 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001784 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001785 // figure out what to do with offset, which is accumulating
1786 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001787 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001788 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001789 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001790 offset = nextOffset;
1791 }
John Kessenich140f3df2015-06-26 16:58:36 -06001792
John Kessenichf85e8062015-12-19 13:57:10 -07001793 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001794 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001795
John Kessenich140f3df2015-06-26 16:58:36 -06001796 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001797 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1798 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001799 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001800 }
1801 }
1802
1803 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001804 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001805 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001806 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001807 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001808 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001809 }
John Kessenich140f3df2015-06-26 16:58:36 -06001810 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001811 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001812 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001813 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001814 if (type.getQualifier().hasXfbBuffer())
1815 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1816 }
1817 }
1818 break;
1819 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001820 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001821 break;
1822 }
1823
1824 if (type.isMatrix())
1825 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1826 else {
1827 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1828 if (type.getVectorSize() > 1)
1829 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1830 }
1831
1832 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001833 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1834
John Kessenichc9a80832015-09-12 12:17:44 -06001835 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001836 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001837 // We need to decorate array strides for types needing explicit layout, except blocks.
1838 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001839 // Use a dummy glslang type for querying internal strides of
1840 // arrays of arrays, but using just a one-dimensional array.
1841 glslang::TType simpleArrayType(type, 0); // deference type of the array
1842 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1843 simpleArrayType.getArraySizes().dereference();
1844
1845 // Will compute the higher-order strides here, rather than making a whole
1846 // pile of types and doing repetitive recursion on their contents.
1847 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1848 }
John Kessenichf8842e52016-01-04 19:22:56 -07001849
1850 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001851 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001852 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001853 if (stride > 0)
1854 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001855 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001856 }
1857 } else {
1858 // single-dimensional array, and don't yet have stride
1859
John Kessenichf8842e52016-01-04 19:22:56 -07001860 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001861 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1862 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001863 }
John Kessenich31ed4832015-09-09 17:51:38 -06001864
John Kessenichc9a80832015-09-12 12:17:44 -06001865 // Do the outer dimension, which might not be known for a runtime-sized array
1866 if (type.isRuntimeSizedArray()) {
1867 spvType = builder.makeRuntimeArray(spvType);
1868 } else {
1869 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001870 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001871 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001872 if (stride > 0)
1873 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001874 }
1875
1876 return spvType;
1877}
1878
John Kessenich6c292d32016-02-15 20:58:50 -07001879// Turn the expression forming the array size into an id.
1880// This is not quite trivial, because of specialization constants.
1881// Sometimes, a raw constant is turned into an Id, and sometimes
1882// a specialization constant expression is.
1883spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1884{
1885 // First, see if this is sized with a node, meaning a specialization constant:
1886 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1887 if (specNode != nullptr) {
1888 builder.clearAccessChain();
1889 specNode->traverse(this);
1890 return accessChainLoad(specNode->getAsTyped()->getType());
1891 }
1892
1893 // Otherwise, need a compile-time (front end) size, get it:
1894 int size = arraySizes.getDimSize(dim);
1895 assert(size > 0);
1896 return builder.makeUintConstant(size);
1897}
1898
John Kessenich103bef92016-02-08 21:38:15 -07001899// Wrap the builder's accessChainLoad to:
1900// - localize handling of RelaxedPrecision
1901// - use the SPIR-V inferred type instead of another conversion of the glslang type
1902// (avoids unnecessary work and possible type punning for structures)
1903// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001904spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1905{
John Kessenich103bef92016-02-08 21:38:15 -07001906 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1907 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1908
1909 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08001910 if (type.getBasicType() == glslang::EbtBool) {
1911 if (builder.isScalarType(nominalTypeId)) {
1912 // Conversion for bool
1913 spv::Id boolType = builder.makeBoolType();
1914 if (nominalTypeId != boolType)
1915 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
1916 } else if (builder.isVectorType(nominalTypeId)) {
1917 // Conversion for bvec
1918 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1919 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1920 if (nominalTypeId != bvecType)
1921 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
1922 }
1923 }
John Kessenich103bef92016-02-08 21:38:15 -07001924
1925 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07001926}
1927
Rex Xu27253232016-02-23 17:51:09 +08001928// Wrap the builder's accessChainStore to:
1929// - do conversion of concrete to abstract type
1930void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
1931{
1932 // Need to convert to abstract types when necessary
1933 if (type.getBasicType() == glslang::EbtBool) {
1934 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1935
1936 if (builder.isScalarType(nominalTypeId)) {
1937 // Conversion for bool
1938 spv::Id boolType = builder.makeBoolType();
1939 if (nominalTypeId != boolType) {
1940 spv::Id zero = builder.makeUintConstant(0);
1941 spv::Id one = builder.makeUintConstant(1);
1942 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
1943 }
1944 } else if (builder.isVectorType(nominalTypeId)) {
1945 // Conversion for bvec
1946 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1947 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1948 if (nominalTypeId != bvecType) {
1949 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
1950 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
1951 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
1952 }
1953 }
1954 }
1955
1956 builder.accessChainStore(rvalue);
1957}
1958
John Kessenichf85e8062015-12-19 13:57:10 -07001959// Decide whether or not this type should be
1960// decorated with offsets and strides, and if so
1961// whether std140 or std430 rules should be applied.
1962glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001963{
John Kessenichf85e8062015-12-19 13:57:10 -07001964 // has to be a block
1965 if (type.getBasicType() != glslang::EbtBlock)
1966 return glslang::ElpNone;
1967
1968 // has to be a uniform or buffer block
1969 if (type.getQualifier().storage != glslang::EvqUniform &&
1970 type.getQualifier().storage != glslang::EvqBuffer)
1971 return glslang::ElpNone;
1972
1973 // return the layout to use
1974 switch (type.getQualifier().layoutPacking) {
1975 case glslang::ElpStd140:
1976 case glslang::ElpStd430:
1977 return type.getQualifier().layoutPacking;
1978 default:
1979 return glslang::ElpNone;
1980 }
John Kessenich31ed4832015-09-09 17:51:38 -06001981}
1982
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001983// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001984int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001985{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001986 int size;
John Kessenich49987892015-12-29 17:11:44 -07001987 int stride;
1988 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001989
1990 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001991}
1992
John Kessenich49987892015-12-29 17:11:44 -07001993// 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 -07001994// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001995int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001996{
John Kessenich49987892015-12-29 17:11:44 -07001997 glslang::TType elementType;
1998 elementType.shallowCopy(matrixType);
1999 elementType.clearArraySizes();
2000
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002001 int size;
John Kessenich49987892015-12-29 17:11:44 -07002002 int stride;
2003 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2004
2005 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002006}
2007
John Kessenich5e4b1242015-08-06 22:53:06 -06002008// Given a member type of a struct, realign the current offset for it, and compute
2009// the next (not yet aligned) offset for the next member, which will get aligned
2010// on the next call.
2011// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2012// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2013// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002014void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002015 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002016{
2017 // this will get a positive value when deemed necessary
2018 nextOffset = -1;
2019
John Kessenich5e4b1242015-08-06 22:53:06 -06002020 // override anything in currentOffset with user-set offset
2021 if (memberType.getQualifier().hasOffset())
2022 currentOffset = memberType.getQualifier().layoutOffset;
2023
2024 // It could be that current linker usage in glslang updated all the layoutOffset,
2025 // in which case the following code does not matter. But, that's not quite right
2026 // once cross-compilation unit GLSL validation is done, as the original user
2027 // settings are needed in layoutOffset, and then the following will come into play.
2028
John Kessenichf85e8062015-12-19 13:57:10 -07002029 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002030 if (! memberType.getQualifier().hasOffset())
2031 currentOffset = -1;
2032
2033 return;
2034 }
2035
John Kessenichf85e8062015-12-19 13:57:10 -07002036 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002037 if (currentOffset < 0)
2038 currentOffset = 0;
2039
2040 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2041 // but possibly not yet correctly aligned.
2042
2043 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002044 int dummyStride;
2045 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002046 glslang::RoundToPow2(currentOffset, memberAlignment);
2047 nextOffset = currentOffset + memberSize;
2048}
2049
John Kessenich140f3df2015-06-26 16:58:36 -06002050bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2051{
2052 return node->getName() == "main(";
2053}
2054
2055// Make all the functions, skeletally, without actually visiting their bodies.
2056void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2057{
2058 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2059 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2060 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2061 continue;
2062
2063 // We're on a user function. Set up the basic interface for the function now,
2064 // so that it's available to call.
2065 // Translating the body will happen later.
2066 //
2067 // Typically (except for a "const in" parameter), an address will be passed to the
2068 // function. What it is an address of varies:
2069 //
2070 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2071 // so that write needs to be to a copy, hence the address of a copy works.
2072 //
2073 // - "const in" parameters can just be the r-value, as no writes need occur.
2074 //
2075 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2076 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2077
2078 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002079 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002080 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2081
2082 for (int p = 0; p < (int)parameters.size(); ++p) {
2083 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2084 spv::Id typeId = convertGlslangToSpvType(paramType);
2085 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2086 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2087 else
2088 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002089 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002090 paramTypes.push_back(typeId);
2091 }
2092
2093 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002094 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2095 convertGlslangToSpvType(glslFunction->getType()),
2096 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002097
2098 // Track function to emit/call later
2099 functionMap[glslFunction->getName().c_str()] = function;
2100
2101 // Set the parameter id's
2102 for (int p = 0; p < (int)parameters.size(); ++p) {
2103 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2104 // give a name too
2105 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2106 }
2107 }
2108}
2109
2110// Process all the initializers, while skipping the functions and link objects
2111void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2112{
2113 builder.setBuildPoint(shaderEntry->getLastBlock());
2114 for (int i = 0; i < (int)initializers.size(); ++i) {
2115 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2116 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2117
2118 // We're on a top-level node that's not a function. Treat as an initializer, whose
2119 // code goes into the beginning of main.
2120 initializer->traverse(this);
2121 }
2122 }
2123}
2124
2125// Process all the functions, while skipping initializers.
2126void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2127{
2128 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2129 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2130 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2131 node->traverse(this);
2132 }
2133}
2134
2135void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2136{
2137 // SPIR-V functions should already be in the functionMap from the prepass
2138 // that called makeFunctions().
2139 spv::Function* function = functionMap[node->getName().c_str()];
2140 spv::Block* functionBlock = function->getEntryBlock();
2141 builder.setBuildPoint(functionBlock);
2142}
2143
Rex Xu04db3f52015-09-16 11:44:02 +08002144void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002145{
Rex Xufc618912015-09-09 16:42:49 +08002146 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002147
2148 glslang::TSampler sampler = {};
2149 bool cubeCompare = false;
2150 if (node.isTexture()) {
2151 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2152 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2153 }
2154
John Kessenich140f3df2015-06-26 16:58:36 -06002155 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2156 builder.clearAccessChain();
2157 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002158
2159 // Special case l-value operands
2160 bool lvalue = false;
2161 switch (node.getOp()) {
2162 case glslang::EOpImageAtomicAdd:
2163 case glslang::EOpImageAtomicMin:
2164 case glslang::EOpImageAtomicMax:
2165 case glslang::EOpImageAtomicAnd:
2166 case glslang::EOpImageAtomicOr:
2167 case glslang::EOpImageAtomicXor:
2168 case glslang::EOpImageAtomicExchange:
2169 case glslang::EOpImageAtomicCompSwap:
2170 if (i == 0)
2171 lvalue = true;
2172 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002173 case glslang::EOpSparseTexture:
2174 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2175 lvalue = true;
2176 break;
2177 case glslang::EOpSparseTextureClamp:
2178 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2179 lvalue = true;
2180 break;
2181 case glslang::EOpSparseTextureLod:
2182 case glslang::EOpSparseTextureOffset:
2183 if (i == 3)
2184 lvalue = true;
2185 break;
2186 case glslang::EOpSparseTextureFetch:
2187 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2188 lvalue = true;
2189 break;
2190 case glslang::EOpSparseTextureFetchOffset:
2191 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2192 lvalue = true;
2193 break;
2194 case glslang::EOpSparseTextureLodOffset:
2195 case glslang::EOpSparseTextureGrad:
2196 case glslang::EOpSparseTextureOffsetClamp:
2197 if (i == 4)
2198 lvalue = true;
2199 break;
2200 case glslang::EOpSparseTextureGradOffset:
2201 case glslang::EOpSparseTextureGradClamp:
2202 if (i == 5)
2203 lvalue = true;
2204 break;
2205 case glslang::EOpSparseTextureGradOffsetClamp:
2206 if (i == 6)
2207 lvalue = true;
2208 break;
2209 case glslang::EOpSparseTextureGather:
2210 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2211 lvalue = true;
2212 break;
2213 case glslang::EOpSparseTextureGatherOffset:
2214 case glslang::EOpSparseTextureGatherOffsets:
2215 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2216 lvalue = true;
2217 break;
Rex Xufc618912015-09-09 16:42:49 +08002218 default:
2219 break;
2220 }
2221
Rex Xu6b86d492015-09-16 17:48:22 +08002222 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002223 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002224 else
John Kessenich32cfd492016-02-02 12:37:46 -07002225 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002226 }
2227}
2228
John Kessenichfc51d282015-08-19 13:34:18 -06002229void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002230{
John Kessenichfc51d282015-08-19 13:34:18 -06002231 builder.clearAccessChain();
2232 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002233 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002234}
John Kessenich140f3df2015-06-26 16:58:36 -06002235
John Kessenichfc51d282015-08-19 13:34:18 -06002236spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2237{
Rex Xufc618912015-09-09 16:42:49 +08002238 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002239 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002240 }
2241
John Kessenichfc51d282015-08-19 13:34:18 -06002242 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002243 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2244 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2245 std::vector<spv::Id> arguments;
2246 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002247 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002248 else
2249 translateArguments(*node->getAsUnaryNode(), arguments);
2250 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2251
2252 spv::Builder::TextureParameters params = { };
2253 params.sampler = arguments[0];
2254
Rex Xu04db3f52015-09-16 11:44:02 +08002255 glslang::TCrackedTextureOp cracked;
2256 node->crackTexture(sampler, cracked);
2257
John Kessenichfc51d282015-08-19 13:34:18 -06002258 // Check for queries
2259 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002260 // a sampled image needs to have the image extracted first
2261 if (builder.isSampledImage(params.sampler))
2262 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002263 switch (node->getOp()) {
2264 case glslang::EOpImageQuerySize:
2265 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002266 if (arguments.size() > 1) {
2267 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002268 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002269 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002270 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002271 case glslang::EOpImageQuerySamples:
2272 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002273 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002274 case glslang::EOpTextureQueryLod:
2275 params.coords = arguments[1];
2276 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2277 case glslang::EOpTextureQueryLevels:
2278 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002279 case glslang::EOpSparseTexelsResident:
2280 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002281 default:
2282 assert(0);
2283 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002284 }
John Kessenich140f3df2015-06-26 16:58:36 -06002285 }
2286
Rex Xufc618912015-09-09 16:42:49 +08002287 // Check for image functions other than queries
2288 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002289 std::vector<spv::Id> operands;
2290 auto opIt = arguments.begin();
2291 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002292
2293 // Handle subpass operations
2294 // TODO: GLSL should change to have the "MS" only on the type rather than the
2295 // built-in function.
2296 if (cracked.subpass) {
2297 // add on the (0,0) coordinate
2298 spv::Id zero = builder.makeIntConstant(0);
2299 std::vector<spv::Id> comps;
2300 comps.push_back(zero);
2301 comps.push_back(zero);
2302 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2303 if (sampler.ms) {
2304 operands.push_back(spv::ImageOperandsSampleMask);
2305 operands.push_back(*(opIt++));
2306 }
2307 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2308 }
2309
John Kessenich56bab042015-09-16 10:54:31 -06002310 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002311 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002312 if (sampler.ms) {
2313 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002314 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002315 }
John Kessenich56bab042015-09-16 10:54:31 -06002316 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002317 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2318 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002319 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002320 if (sampler.ms) {
2321 operands.push_back(*(opIt + 1));
2322 operands.push_back(spv::ImageOperandsSampleMask);
2323 operands.push_back(*opIt);
2324 } else
2325 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002326 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002327 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2328 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002329 return spv::NoResult;
Rex Xu48edadf2015-12-31 16:11:41 +08002330 } else if (node->isSparseImage()) {
2331 spv::MissingFunctionality("sparse image functions");
2332 return spv::NoResult;
John Kessenichcd261442016-01-22 09:54:12 -07002333 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002334 // Process image atomic operations
2335
2336 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2337 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002338 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002339
Rex Xufc618912015-09-09 16:42:49 +08002340 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002341 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002342
2343 std::vector<spv::Id> operands;
2344 operands.push_back(pointer);
2345 for (; opIt != arguments.end(); ++opIt)
2346 operands.push_back(*opIt);
2347
Rex Xu04db3f52015-09-16 11:44:02 +08002348 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002349 }
2350 }
2351
2352 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002353 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002354 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2355
John Kessenichfc51d282015-08-19 13:34:18 -06002356 // check for bias argument
2357 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002358 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002359 int nonBiasArgCount = 2;
2360 if (cracked.offset)
2361 ++nonBiasArgCount;
2362 if (cracked.grad)
2363 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002364 if (cracked.lodClamp)
2365 ++nonBiasArgCount;
2366 if (sparse)
2367 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002368
2369 if ((int)arguments.size() > nonBiasArgCount)
2370 bias = true;
2371 }
2372
John Kessenichfc51d282015-08-19 13:34:18 -06002373 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002374
John Kessenichfc51d282015-08-19 13:34:18 -06002375 params.coords = arguments[1];
2376 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002377 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002378
2379 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002380 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002381 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002382 ++extraArgs;
2383 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002384 params.Dref = arguments[2];
2385 ++extraArgs;
2386 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002387 std::vector<spv::Id> indexes;
2388 int comp;
2389 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002390 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002391 else
2392 comp = builder.getNumComponents(params.coords) - 1;
2393 indexes.push_back(comp);
2394 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2395 }
2396 if (cracked.lod) {
2397 params.lod = arguments[2];
2398 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002399 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2400 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2401 noImplicitLod = true;
2402 }
2403 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002404 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002405 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002406 }
2407 if (cracked.grad) {
2408 params.gradX = arguments[2 + extraArgs];
2409 params.gradY = arguments[3 + extraArgs];
2410 extraArgs += 2;
2411 }
John Kessenich55e7d112015-11-15 21:33:39 -07002412 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002413 params.offset = arguments[2 + extraArgs];
2414 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002415 } else if (cracked.offsets) {
2416 params.offsets = arguments[2 + extraArgs];
2417 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002418 }
Rex Xu48edadf2015-12-31 16:11:41 +08002419 if (cracked.lodClamp) {
2420 params.lodClamp = arguments[2 + extraArgs];
2421 ++extraArgs;
2422 }
2423 if (sparse) {
2424 params.texelOut = arguments[2 + extraArgs];
2425 ++extraArgs;
2426 }
John Kessenichfc51d282015-08-19 13:34:18 -06002427 if (bias) {
2428 params.bias = arguments[2 + extraArgs];
2429 ++extraArgs;
2430 }
John Kessenich55e7d112015-11-15 21:33:39 -07002431 if (cracked.gather && ! sampler.shadow) {
2432 // default component is 0, if missing, otherwise an argument
2433 if (2 + extraArgs < (int)arguments.size()) {
2434 params.comp = arguments[2 + extraArgs];
2435 ++extraArgs;
2436 } else {
2437 params.comp = builder.makeIntConstant(0);
2438 }
2439 }
John Kessenichfc51d282015-08-19 13:34:18 -06002440
John Kessenich019f08f2016-02-15 15:40:42 -07002441 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002442}
2443
2444spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2445{
2446 // Grab the function's pointer from the previously created function
2447 spv::Function* function = functionMap[node->getName().c_str()];
2448 if (! function)
2449 return 0;
2450
2451 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2452 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2453
2454 // See comments in makeFunctions() for details about the semantics for parameter passing.
2455 //
2456 // These imply we need a four step process:
2457 // 1. Evaluate the arguments
2458 // 2. Allocate and make copies of in, out, and inout arguments
2459 // 3. Make the call
2460 // 4. Copy back the results
2461
2462 // 1. Evaluate the arguments
2463 std::vector<spv::Builder::AccessChain> lValues;
2464 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002465 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002466 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2467 // build l-value
2468 builder.clearAccessChain();
2469 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002470 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002471 // keep outputs as l-values, evaluate input-only as r-values
2472 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2473 // save l-value
2474 lValues.push_back(builder.getAccessChain());
2475 } else {
2476 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002477 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002478 }
2479 }
2480
2481 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2482 // copy the original into that space.
2483 //
2484 // Also, build up the list of actual arguments to pass in for the call
2485 int lValueCount = 0;
2486 int rValueCount = 0;
2487 std::vector<spv::Id> spvArgs;
2488 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2489 spv::Id arg;
2490 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2491 // need space to hold the copy
2492 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2493 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2494 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2495 // need to copy the input into output space
2496 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002497 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002498 builder.createStore(copy, arg);
2499 }
2500 ++lValueCount;
2501 } else {
2502 arg = rValues[rValueCount];
2503 ++rValueCount;
2504 }
2505 spvArgs.push_back(arg);
2506 }
2507
2508 // 3. Make the call.
2509 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002510 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002511
2512 // 4. Copy back out an "out" arguments.
2513 lValueCount = 0;
2514 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2515 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2516 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2517 spv::Id copy = builder.createLoad(spvArgs[a]);
2518 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002519 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002520 }
2521 ++lValueCount;
2522 }
2523 }
2524
2525 return result;
2526}
2527
2528// Translate AST operation to SPV operation, already having SPV-based operands/types.
2529spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2530 spv::Id typeId, spv::Id left, spv::Id right,
2531 glslang::TBasicType typeProxy, bool reduceComparison)
2532{
2533 bool isUnsigned = typeProxy == glslang::EbtUint;
2534 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2535
2536 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002537 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002538 bool comparison = false;
2539
2540 switch (op) {
2541 case glslang::EOpAdd:
2542 case glslang::EOpAddAssign:
2543 if (isFloat)
2544 binOp = spv::OpFAdd;
2545 else
2546 binOp = spv::OpIAdd;
2547 break;
2548 case glslang::EOpSub:
2549 case glslang::EOpSubAssign:
2550 if (isFloat)
2551 binOp = spv::OpFSub;
2552 else
2553 binOp = spv::OpISub;
2554 break;
2555 case glslang::EOpMul:
2556 case glslang::EOpMulAssign:
2557 if (isFloat)
2558 binOp = spv::OpFMul;
2559 else
2560 binOp = spv::OpIMul;
2561 break;
2562 case glslang::EOpVectorTimesScalar:
2563 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002564 if (isFloat) {
2565 if (builder.isVector(right))
2566 std::swap(left, right);
2567 assert(builder.isScalar(right));
2568 needMatchingVectors = false;
2569 binOp = spv::OpVectorTimesScalar;
2570 } else
2571 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002572 break;
2573 case glslang::EOpVectorTimesMatrix:
2574 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002575 binOp = spv::OpVectorTimesMatrix;
2576 break;
2577 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002578 binOp = spv::OpMatrixTimesVector;
2579 break;
2580 case glslang::EOpMatrixTimesScalar:
2581 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002582 binOp = spv::OpMatrixTimesScalar;
2583 break;
2584 case glslang::EOpMatrixTimesMatrix:
2585 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002586 binOp = spv::OpMatrixTimesMatrix;
2587 break;
2588 case glslang::EOpOuterProduct:
2589 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002590 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002591 break;
2592
2593 case glslang::EOpDiv:
2594 case glslang::EOpDivAssign:
2595 if (isFloat)
2596 binOp = spv::OpFDiv;
2597 else if (isUnsigned)
2598 binOp = spv::OpUDiv;
2599 else
2600 binOp = spv::OpSDiv;
2601 break;
2602 case glslang::EOpMod:
2603 case glslang::EOpModAssign:
2604 if (isFloat)
2605 binOp = spv::OpFMod;
2606 else if (isUnsigned)
2607 binOp = spv::OpUMod;
2608 else
2609 binOp = spv::OpSMod;
2610 break;
2611 case glslang::EOpRightShift:
2612 case glslang::EOpRightShiftAssign:
2613 if (isUnsigned)
2614 binOp = spv::OpShiftRightLogical;
2615 else
2616 binOp = spv::OpShiftRightArithmetic;
2617 break;
2618 case glslang::EOpLeftShift:
2619 case glslang::EOpLeftShiftAssign:
2620 binOp = spv::OpShiftLeftLogical;
2621 break;
2622 case glslang::EOpAnd:
2623 case glslang::EOpAndAssign:
2624 binOp = spv::OpBitwiseAnd;
2625 break;
2626 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002627 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002628 binOp = spv::OpLogicalAnd;
2629 break;
2630 case glslang::EOpInclusiveOr:
2631 case glslang::EOpInclusiveOrAssign:
2632 binOp = spv::OpBitwiseOr;
2633 break;
2634 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002635 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002636 binOp = spv::OpLogicalOr;
2637 break;
2638 case glslang::EOpExclusiveOr:
2639 case glslang::EOpExclusiveOrAssign:
2640 binOp = spv::OpBitwiseXor;
2641 break;
2642 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002643 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002644 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002645 break;
2646
2647 case glslang::EOpLessThan:
2648 case glslang::EOpGreaterThan:
2649 case glslang::EOpLessThanEqual:
2650 case glslang::EOpGreaterThanEqual:
2651 case glslang::EOpEqual:
2652 case glslang::EOpNotEqual:
2653 case glslang::EOpVectorEqual:
2654 case glslang::EOpVectorNotEqual:
2655 comparison = true;
2656 break;
2657 default:
2658 break;
2659 }
2660
John Kessenich7c1aa102015-10-15 13:29:11 -06002661 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002662 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002663 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002664 if (builder.isMatrix(left) || builder.isMatrix(right))
2665 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002666
2667 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002668 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002669 builder.promoteScalar(precision, left, right);
2670
John Kessenich32cfd492016-02-02 12:37:46 -07002671 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002672 }
2673
2674 if (! comparison)
2675 return 0;
2676
John Kessenich7c1aa102015-10-15 13:29:11 -06002677 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002678
2679 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2680 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2681
John Kessenich22118352015-12-21 20:54:09 -07002682 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002683 }
2684
2685 switch (op) {
2686 case glslang::EOpLessThan:
2687 if (isFloat)
2688 binOp = spv::OpFOrdLessThan;
2689 else if (isUnsigned)
2690 binOp = spv::OpULessThan;
2691 else
2692 binOp = spv::OpSLessThan;
2693 break;
2694 case glslang::EOpGreaterThan:
2695 if (isFloat)
2696 binOp = spv::OpFOrdGreaterThan;
2697 else if (isUnsigned)
2698 binOp = spv::OpUGreaterThan;
2699 else
2700 binOp = spv::OpSGreaterThan;
2701 break;
2702 case glslang::EOpLessThanEqual:
2703 if (isFloat)
2704 binOp = spv::OpFOrdLessThanEqual;
2705 else if (isUnsigned)
2706 binOp = spv::OpULessThanEqual;
2707 else
2708 binOp = spv::OpSLessThanEqual;
2709 break;
2710 case glslang::EOpGreaterThanEqual:
2711 if (isFloat)
2712 binOp = spv::OpFOrdGreaterThanEqual;
2713 else if (isUnsigned)
2714 binOp = spv::OpUGreaterThanEqual;
2715 else
2716 binOp = spv::OpSGreaterThanEqual;
2717 break;
2718 case glslang::EOpEqual:
2719 case glslang::EOpVectorEqual:
2720 if (isFloat)
2721 binOp = spv::OpFOrdEqual;
2722 else
2723 binOp = spv::OpIEqual;
2724 break;
2725 case glslang::EOpNotEqual:
2726 case glslang::EOpVectorNotEqual:
2727 if (isFloat)
2728 binOp = spv::OpFOrdNotEqual;
2729 else
2730 binOp = spv::OpINotEqual;
2731 break;
2732 default:
2733 break;
2734 }
2735
John Kessenich32cfd492016-02-02 12:37:46 -07002736 if (binOp != spv::OpNop)
2737 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002738
2739 return 0;
2740}
2741
John Kessenich04bb8a02015-12-12 12:28:14 -07002742//
2743// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2744// These can be any of:
2745//
2746// matrix * scalar
2747// scalar * matrix
2748// matrix * matrix linear algebraic
2749// matrix * vector
2750// vector * matrix
2751// matrix * matrix componentwise
2752// matrix op matrix op in {+, -, /}
2753// matrix op scalar op in {+, -, /}
2754// scalar op matrix op in {+, -, /}
2755//
2756spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2757{
2758 bool firstClass = true;
2759
2760 // First, handle first-class matrix operations (* and matrix/scalar)
2761 switch (op) {
2762 case spv::OpFDiv:
2763 if (builder.isMatrix(left) && builder.isScalar(right)) {
2764 // turn matrix / scalar into a multiply...
2765 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2766 op = spv::OpMatrixTimesScalar;
2767 } else
2768 firstClass = false;
2769 break;
2770 case spv::OpMatrixTimesScalar:
2771 if (builder.isMatrix(right))
2772 std::swap(left, right);
2773 assert(builder.isScalar(right));
2774 break;
2775 case spv::OpVectorTimesMatrix:
2776 assert(builder.isVector(left));
2777 assert(builder.isMatrix(right));
2778 break;
2779 case spv::OpMatrixTimesVector:
2780 assert(builder.isMatrix(left));
2781 assert(builder.isVector(right));
2782 break;
2783 case spv::OpMatrixTimesMatrix:
2784 assert(builder.isMatrix(left));
2785 assert(builder.isMatrix(right));
2786 break;
2787 default:
2788 firstClass = false;
2789 break;
2790 }
2791
John Kessenich32cfd492016-02-02 12:37:46 -07002792 if (firstClass)
2793 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002794
2795 // Handle component-wise +, -, *, and / for all combinations of type.
2796 // The result type of all of them is the same type as the (a) matrix operand.
2797 // The algorithm is to:
2798 // - break the matrix(es) into vectors
2799 // - smear any scalar to a vector
2800 // - do vector operations
2801 // - make a matrix out the vector results
2802 switch (op) {
2803 case spv::OpFAdd:
2804 case spv::OpFSub:
2805 case spv::OpFDiv:
2806 case spv::OpFMul:
2807 {
2808 // one time set up...
2809 bool leftMat = builder.isMatrix(left);
2810 bool rightMat = builder.isMatrix(right);
2811 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2812 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2813 spv::Id scalarType = builder.getScalarTypeId(typeId);
2814 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2815 std::vector<spv::Id> results;
2816 spv::Id smearVec = spv::NoResult;
2817 if (builder.isScalar(left))
2818 smearVec = builder.smearScalar(precision, left, vecType);
2819 else if (builder.isScalar(right))
2820 smearVec = builder.smearScalar(precision, right, vecType);
2821
2822 // do each vector op
2823 for (unsigned int c = 0; c < numCols; ++c) {
2824 std::vector<unsigned int> indexes;
2825 indexes.push_back(c);
2826 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2827 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2828 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2829 builder.setPrecision(results.back(), precision);
2830 }
2831
2832 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002833 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002834 }
2835 default:
2836 assert(0);
2837 return spv::NoResult;
2838 }
2839}
2840
Rex Xu04db3f52015-09-16 11:44:02 +08002841spv::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 -06002842{
2843 spv::Op unaryOp = spv::OpNop;
2844 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002845 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002846 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002847
2848 switch (op) {
2849 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002850 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002851 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002852 if (builder.isMatrixType(typeId))
2853 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2854 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002855 unaryOp = spv::OpSNegate;
2856 break;
2857
2858 case glslang::EOpLogicalNot:
2859 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002860 unaryOp = spv::OpLogicalNot;
2861 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002862 case glslang::EOpBitwiseNot:
2863 unaryOp = spv::OpNot;
2864 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002865
John Kessenich140f3df2015-06-26 16:58:36 -06002866 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002867 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002868 break;
2869 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002870 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002871 break;
2872 case glslang::EOpTranspose:
2873 unaryOp = spv::OpTranspose;
2874 break;
2875
2876 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002877 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002878 break;
2879 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002880 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002881 break;
2882 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002883 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002884 break;
2885 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002886 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002887 break;
2888 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002889 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002890 break;
2891 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002892 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002893 break;
2894 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002895 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002896 break;
2897 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002898 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002899 break;
2900
2901 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002902 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002903 break;
2904 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002905 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002906 break;
2907 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002908 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002909 break;
2910 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002911 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002912 break;
2913 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002914 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002915 break;
2916 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002917 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002918 break;
2919
2920 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002921 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002922 break;
2923 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002924 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002925 break;
2926
2927 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002928 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002929 break;
2930 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002931 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002932 break;
2933 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002934 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002935 break;
2936 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002937 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002938 break;
2939 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002940 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002941 break;
2942 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002943 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002944 break;
2945
2946 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002947 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002948 break;
2949 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002950 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002951 break;
2952 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002953 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002954 break;
2955 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002956 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002957 break;
2958 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002959 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002960 break;
2961 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002962 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002963 break;
2964
2965 case glslang::EOpIsNan:
2966 unaryOp = spv::OpIsNan;
2967 break;
2968 case glslang::EOpIsInf:
2969 unaryOp = spv::OpIsInf;
2970 break;
2971
Rex Xucbc426e2015-12-15 16:03:10 +08002972 case glslang::EOpFloatBitsToInt:
2973 case glslang::EOpFloatBitsToUint:
2974 case glslang::EOpIntBitsToFloat:
2975 case glslang::EOpUintBitsToFloat:
2976 unaryOp = spv::OpBitcast;
2977 break;
2978
John Kessenich140f3df2015-06-26 16:58:36 -06002979 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002980 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002981 break;
2982 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002983 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002984 break;
2985 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002986 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002987 break;
2988 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002989 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002990 break;
2991 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002992 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002993 break;
2994 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002995 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002996 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002997 case glslang::EOpPackSnorm4x8:
2998 libCall = spv::GLSLstd450PackSnorm4x8;
2999 break;
3000 case glslang::EOpUnpackSnorm4x8:
3001 libCall = spv::GLSLstd450UnpackSnorm4x8;
3002 break;
3003 case glslang::EOpPackUnorm4x8:
3004 libCall = spv::GLSLstd450PackUnorm4x8;
3005 break;
3006 case glslang::EOpUnpackUnorm4x8:
3007 libCall = spv::GLSLstd450UnpackUnorm4x8;
3008 break;
3009 case glslang::EOpPackDouble2x32:
3010 libCall = spv::GLSLstd450PackDouble2x32;
3011 break;
3012 case glslang::EOpUnpackDouble2x32:
3013 libCall = spv::GLSLstd450UnpackDouble2x32;
3014 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003015
3016 case glslang::EOpDPdx:
3017 unaryOp = spv::OpDPdx;
3018 break;
3019 case glslang::EOpDPdy:
3020 unaryOp = spv::OpDPdy;
3021 break;
3022 case glslang::EOpFwidth:
3023 unaryOp = spv::OpFwidth;
3024 break;
3025 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003026 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003027 unaryOp = spv::OpDPdxFine;
3028 break;
3029 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003030 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003031 unaryOp = spv::OpDPdyFine;
3032 break;
3033 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003034 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003035 unaryOp = spv::OpFwidthFine;
3036 break;
3037 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003038 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003039 unaryOp = spv::OpDPdxCoarse;
3040 break;
3041 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003042 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003043 unaryOp = spv::OpDPdyCoarse;
3044 break;
3045 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003046 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003047 unaryOp = spv::OpFwidthCoarse;
3048 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003049 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003050 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003051 libCall = spv::GLSLstd450InterpolateAtCentroid;
3052 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003053 case glslang::EOpAny:
3054 unaryOp = spv::OpAny;
3055 break;
3056 case glslang::EOpAll:
3057 unaryOp = spv::OpAll;
3058 break;
3059
3060 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003061 if (isFloat)
3062 libCall = spv::GLSLstd450FAbs;
3063 else
3064 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003065 break;
3066 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003067 if (isFloat)
3068 libCall = spv::GLSLstd450FSign;
3069 else
3070 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003071 break;
3072
John Kessenichfc51d282015-08-19 13:34:18 -06003073 case glslang::EOpAtomicCounterIncrement:
3074 case glslang::EOpAtomicCounterDecrement:
3075 case glslang::EOpAtomicCounter:
3076 {
3077 // Handle all of the atomics in one place, in createAtomicOperation()
3078 std::vector<spv::Id> operands;
3079 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003080 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003081 }
3082
John Kessenichfc51d282015-08-19 13:34:18 -06003083 case glslang::EOpBitFieldReverse:
3084 unaryOp = spv::OpBitReverse;
3085 break;
3086 case glslang::EOpBitCount:
3087 unaryOp = spv::OpBitCount;
3088 break;
3089 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003090 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003091 break;
3092 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003093 if (isUnsigned)
3094 libCall = spv::GLSLstd450FindUMsb;
3095 else
3096 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003097 break;
3098
John Kessenich140f3df2015-06-26 16:58:36 -06003099 default:
3100 return 0;
3101 }
3102
3103 spv::Id id;
3104 if (libCall >= 0) {
3105 std::vector<spv::Id> args;
3106 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003107 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003108 } else
3109 id = builder.createUnaryOp(unaryOp, typeId, operand);
3110
John Kessenich32cfd492016-02-02 12:37:46 -07003111 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003112}
3113
John Kessenich7a53f762016-01-20 11:19:27 -07003114// Create a unary operation on a matrix
3115spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3116{
3117 // Handle unary operations vector by vector.
3118 // The result type is the same type as the original type.
3119 // The algorithm is to:
3120 // - break the matrix into vectors
3121 // - apply the operation to each vector
3122 // - make a matrix out the vector results
3123
3124 // get the types sorted out
3125 int numCols = builder.getNumColumns(operand);
3126 int numRows = builder.getNumRows(operand);
3127 spv::Id scalarType = builder.getScalarTypeId(typeId);
3128 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3129 std::vector<spv::Id> results;
3130
3131 // do each vector op
3132 for (int c = 0; c < numCols; ++c) {
3133 std::vector<unsigned int> indexes;
3134 indexes.push_back(c);
3135 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3136 results.push_back(builder.createUnaryOp(op, vecType, vec));
3137 builder.setPrecision(results.back(), precision);
3138 }
3139
3140 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003141 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003142}
3143
John Kessenich140f3df2015-06-26 16:58:36 -06003144spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3145{
3146 spv::Op convOp = spv::OpNop;
3147 spv::Id zero = 0;
3148 spv::Id one = 0;
3149
3150 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3151
3152 switch (op) {
3153 case glslang::EOpConvIntToBool:
3154 case glslang::EOpConvUintToBool:
3155 zero = builder.makeUintConstant(0);
3156 zero = makeSmearedConstant(zero, vectorSize);
3157 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3158
3159 case glslang::EOpConvFloatToBool:
3160 zero = builder.makeFloatConstant(0.0F);
3161 zero = makeSmearedConstant(zero, vectorSize);
3162 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3163
3164 case glslang::EOpConvDoubleToBool:
3165 zero = builder.makeDoubleConstant(0.0);
3166 zero = makeSmearedConstant(zero, vectorSize);
3167 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3168
3169 case glslang::EOpConvBoolToFloat:
3170 convOp = spv::OpSelect;
3171 zero = builder.makeFloatConstant(0.0);
3172 one = builder.makeFloatConstant(1.0);
3173 break;
3174 case glslang::EOpConvBoolToDouble:
3175 convOp = spv::OpSelect;
3176 zero = builder.makeDoubleConstant(0.0);
3177 one = builder.makeDoubleConstant(1.0);
3178 break;
3179 case glslang::EOpConvBoolToInt:
3180 zero = builder.makeIntConstant(0);
3181 one = builder.makeIntConstant(1);
3182 convOp = spv::OpSelect;
3183 break;
3184 case glslang::EOpConvBoolToUint:
3185 zero = builder.makeUintConstant(0);
3186 one = builder.makeUintConstant(1);
3187 convOp = spv::OpSelect;
3188 break;
3189
3190 case glslang::EOpConvIntToFloat:
3191 case glslang::EOpConvIntToDouble:
3192 convOp = spv::OpConvertSToF;
3193 break;
3194
3195 case glslang::EOpConvUintToFloat:
3196 case glslang::EOpConvUintToDouble:
3197 convOp = spv::OpConvertUToF;
3198 break;
3199
3200 case glslang::EOpConvDoubleToFloat:
3201 case glslang::EOpConvFloatToDouble:
3202 convOp = spv::OpFConvert;
3203 break;
3204
3205 case glslang::EOpConvFloatToInt:
3206 case glslang::EOpConvDoubleToInt:
3207 convOp = spv::OpConvertFToS;
3208 break;
3209
3210 case glslang::EOpConvUintToInt:
3211 case glslang::EOpConvIntToUint:
3212 convOp = spv::OpBitcast;
3213 break;
3214
3215 case glslang::EOpConvFloatToUint:
3216 case glslang::EOpConvDoubleToUint:
3217 convOp = spv::OpConvertFToU;
3218 break;
3219 default:
3220 break;
3221 }
3222
3223 spv::Id result = 0;
3224 if (convOp == spv::OpNop)
3225 return result;
3226
3227 if (convOp == spv::OpSelect) {
3228 zero = makeSmearedConstant(zero, vectorSize);
3229 one = makeSmearedConstant(one, vectorSize);
3230 result = builder.createTriOp(convOp, destType, operand, one, zero);
3231 } else
3232 result = builder.createUnaryOp(convOp, destType, operand);
3233
John Kessenich32cfd492016-02-02 12:37:46 -07003234 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003235}
3236
3237spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3238{
3239 if (vectorSize == 0)
3240 return constant;
3241
3242 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3243 std::vector<spv::Id> components;
3244 for (int c = 0; c < vectorSize; ++c)
3245 components.push_back(constant);
3246 return builder.makeCompositeConstant(vectorTypeId, components);
3247}
3248
John Kessenich426394d2015-07-23 10:22:48 -06003249// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003250spv::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 -06003251{
3252 spv::Op opCode = spv::OpNop;
3253
3254 switch (op) {
3255 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003256 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003257 opCode = spv::OpAtomicIAdd;
3258 break;
3259 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003260 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003261 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003262 break;
3263 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003264 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003265 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003266 break;
3267 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003268 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003269 opCode = spv::OpAtomicAnd;
3270 break;
3271 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003272 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003273 opCode = spv::OpAtomicOr;
3274 break;
3275 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003276 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003277 opCode = spv::OpAtomicXor;
3278 break;
3279 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003280 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003281 opCode = spv::OpAtomicExchange;
3282 break;
3283 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003284 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003285 opCode = spv::OpAtomicCompareExchange;
3286 break;
3287 case glslang::EOpAtomicCounterIncrement:
3288 opCode = spv::OpAtomicIIncrement;
3289 break;
3290 case glslang::EOpAtomicCounterDecrement:
3291 opCode = spv::OpAtomicIDecrement;
3292 break;
3293 case glslang::EOpAtomicCounter:
3294 opCode = spv::OpAtomicLoad;
3295 break;
3296 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003297 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003298 break;
3299 }
3300
3301 // Sort out the operands
3302 // - mapping from glslang -> SPV
3303 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003304 // - compare-exchange swaps the value and comparator
3305 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003306 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3307 auto opIt = operands.begin(); // walk the glslang operands
3308 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003309 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3310 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3311 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003312 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3313 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003314 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003315 spvAtomicOperands.push_back(*(opIt + 1));
3316 spvAtomicOperands.push_back(*opIt);
3317 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003318 }
John Kessenich426394d2015-07-23 10:22:48 -06003319
John Kessenich3e60a6f2015-09-14 22:45:16 -06003320 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003321 for (; opIt != operands.end(); ++opIt)
3322 spvAtomicOperands.push_back(*opIt);
3323
3324 return builder.createOp(opCode, typeId, spvAtomicOperands);
3325}
3326
John Kessenich5e4b1242015-08-06 22:53:06 -06003327spv::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 -06003328{
John Kessenich5e4b1242015-08-06 22:53:06 -06003329 bool isUnsigned = typeProxy == glslang::EbtUint;
3330 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3331
John Kessenich140f3df2015-06-26 16:58:36 -06003332 spv::Op opCode = spv::OpNop;
3333 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003334 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003335 spv::Id typeId0 = 0;
3336 if (consumedOperands > 0)
3337 typeId0 = builder.getTypeId(operands[0]);
3338 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003339
3340 switch (op) {
3341 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003342 if (isFloat)
3343 libCall = spv::GLSLstd450FMin;
3344 else if (isUnsigned)
3345 libCall = spv::GLSLstd450UMin;
3346 else
3347 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003348 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003349 break;
3350 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003351 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003352 break;
3353 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003354 if (isFloat)
3355 libCall = spv::GLSLstd450FMax;
3356 else if (isUnsigned)
3357 libCall = spv::GLSLstd450UMax;
3358 else
3359 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003360 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003361 break;
3362 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003363 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003364 break;
3365 case glslang::EOpDot:
3366 opCode = spv::OpDot;
3367 break;
3368 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003369 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003370 break;
3371
3372 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003373 if (isFloat)
3374 libCall = spv::GLSLstd450FClamp;
3375 else if (isUnsigned)
3376 libCall = spv::GLSLstd450UClamp;
3377 else
3378 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003379 builder.promoteScalar(precision, operands.front(), operands[1]);
3380 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003381 break;
3382 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003383 if (isFloat)
3384 libCall = spv::GLSLstd450FMix;
John Kessenich6c292d32016-02-15 20:58:50 -07003385 else {
3386 opCode = spv::OpSelect;
3387 spv::MissingFunctionality("translating integer mix to OpSelect");
3388 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003389 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003390 break;
3391 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003392 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003393 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003394 break;
3395 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003396 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003397 builder.promoteScalar(precision, operands[0], operands[2]);
3398 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003399 break;
3400
3401 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003402 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003403 break;
3404 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003405 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003406 break;
3407 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003408 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003409 break;
3410 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003411 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003412 break;
3413 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003414 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003415 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003416 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003417 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003418 libCall = spv::GLSLstd450InterpolateAtSample;
3419 break;
3420 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003421 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003422 libCall = spv::GLSLstd450InterpolateAtOffset;
3423 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003424 case glslang::EOpAddCarry:
3425 opCode = spv::OpIAddCarry;
3426 typeId = builder.makeStructResultType(typeId0, typeId0);
3427 consumedOperands = 2;
3428 break;
3429 case glslang::EOpSubBorrow:
3430 opCode = spv::OpISubBorrow;
3431 typeId = builder.makeStructResultType(typeId0, typeId0);
3432 consumedOperands = 2;
3433 break;
3434 case glslang::EOpUMulExtended:
3435 opCode = spv::OpUMulExtended;
3436 typeId = builder.makeStructResultType(typeId0, typeId0);
3437 consumedOperands = 2;
3438 break;
3439 case glslang::EOpIMulExtended:
3440 opCode = spv::OpSMulExtended;
3441 typeId = builder.makeStructResultType(typeId0, typeId0);
3442 consumedOperands = 2;
3443 break;
3444 case glslang::EOpBitfieldExtract:
3445 if (isUnsigned)
3446 opCode = spv::OpBitFieldUExtract;
3447 else
3448 opCode = spv::OpBitFieldSExtract;
3449 break;
3450 case glslang::EOpBitfieldInsert:
3451 opCode = spv::OpBitFieldInsert;
3452 break;
3453
3454 case glslang::EOpFma:
3455 libCall = spv::GLSLstd450Fma;
3456 break;
3457 case glslang::EOpFrexp:
3458 libCall = spv::GLSLstd450FrexpStruct;
3459 if (builder.getNumComponents(operands[0]) == 1)
3460 frexpIntType = builder.makeIntegerType(32, true);
3461 else
3462 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3463 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3464 consumedOperands = 1;
3465 break;
3466 case glslang::EOpLdexp:
3467 libCall = spv::GLSLstd450Ldexp;
3468 break;
3469
John Kessenich140f3df2015-06-26 16:58:36 -06003470 default:
3471 return 0;
3472 }
3473
3474 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003475 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003476 // Use an extended instruction from the standard library.
3477 // Construct the call arguments, without modifying the original operands vector.
3478 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3479 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003480 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003481 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003482 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003483 case 0:
3484 // should all be handled by visitAggregate and createNoArgOperation
3485 assert(0);
3486 return 0;
3487 case 1:
3488 // should all be handled by createUnaryOperation
3489 assert(0);
3490 return 0;
3491 case 2:
3492 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3493 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003494 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003495 // anything 3 or over doesn't have l-value operands, so all should be consumed
3496 assert(consumedOperands == operands.size());
3497 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003498 break;
3499 }
3500 }
3501
John Kessenich55e7d112015-11-15 21:33:39 -07003502 // Decode the return types that were structures
3503 switch (op) {
3504 case glslang::EOpAddCarry:
3505 case glslang::EOpSubBorrow:
3506 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3507 id = builder.createCompositeExtract(id, typeId0, 0);
3508 break;
3509 case glslang::EOpUMulExtended:
3510 case glslang::EOpIMulExtended:
3511 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3512 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3513 break;
3514 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003515 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003516 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3517 id = builder.createCompositeExtract(id, typeId0, 0);
3518 break;
3519 default:
3520 break;
3521 }
3522
John Kessenich32cfd492016-02-02 12:37:46 -07003523 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003524}
3525
3526// Intrinsics with no arguments, no return value, and no precision.
3527spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3528{
3529 // TODO: get the barrier operands correct
3530
3531 switch (op) {
3532 case glslang::EOpEmitVertex:
3533 builder.createNoResultOp(spv::OpEmitVertex);
3534 return 0;
3535 case glslang::EOpEndPrimitive:
3536 builder.createNoResultOp(spv::OpEndPrimitive);
3537 return 0;
3538 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003539 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3540 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003541 return 0;
3542 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003543 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003544 return 0;
3545 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003546 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003547 return 0;
3548 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003549 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003550 return 0;
3551 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003552 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003553 return 0;
3554 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003555 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003556 return 0;
3557 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003558 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003559 return 0;
3560 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003561 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003562 return 0;
3563 }
3564}
3565
3566spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3567{
John Kessenich2f273362015-07-18 22:34:27 -06003568 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003569 spv::Id id;
3570 if (symbolValues.end() != iter) {
3571 id = iter->second;
3572 return id;
3573 }
3574
3575 // it was not found, create it
3576 id = createSpvVariable(symbol);
3577 symbolValues[symbol->getId()] = id;
3578
3579 if (! symbol->getType().isStruct()) {
3580 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003581 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003582 if (symbol->getType().getQualifier().hasSpecConstantId())
3583 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003584 if (symbol->getQualifier().hasLocation())
3585 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3586 if (symbol->getQualifier().hasIndex())
3587 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3588 if (symbol->getQualifier().hasComponent())
3589 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3590 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003591 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003592 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003593 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003594 if (symbol->getQualifier().hasXfbBuffer())
3595 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3596 if (symbol->getQualifier().hasXfbOffset())
3597 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3598 }
3599 }
3600
John Kesseniche0b6cad2015-12-24 10:30:13 -07003601 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003602 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003603 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003604 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003605 }
John Kessenich140f3df2015-06-26 16:58:36 -06003606 if (symbol->getQualifier().hasSet())
3607 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003608 else if (IsDescriptorResource(symbol->getType())) {
3609 // default to 0
3610 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3611 }
John Kessenich140f3df2015-06-26 16:58:36 -06003612 if (symbol->getQualifier().hasBinding())
3613 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003614 if (symbol->getQualifier().hasAttachment())
3615 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003616 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003617 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003618 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003619 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003620 if (symbol->getQualifier().hasXfbBuffer())
3621 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3622 }
3623
3624 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003625 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003626 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003627 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003628
John Kessenich140f3df2015-06-26 16:58:36 -06003629 return id;
3630}
3631
John Kessenich55e7d112015-11-15 21:33:39 -07003632// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003633void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3634{
3635 if (dec != spv::BadValue)
3636 builder.addDecoration(id, dec);
3637}
3638
John Kessenich55e7d112015-11-15 21:33:39 -07003639// If 'dec' is valid, add a one-operand decoration to an object
3640void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3641{
3642 if (dec != spv::BadValue)
3643 builder.addDecoration(id, dec, value);
3644}
3645
3646// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003647void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3648{
3649 if (dec != spv::BadValue)
3650 builder.addMemberDecoration(id, (unsigned)member, dec);
3651}
3652
John Kessenich92187592016-02-01 13:45:25 -07003653// If 'dec' is valid, add a one-operand decoration to a struct member
3654void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3655{
3656 if (dec != spv::BadValue)
3657 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3658}
3659
John Kessenich55e7d112015-11-15 21:33:39 -07003660// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003661// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003662//
3663// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3664//
3665// Recursively walk the nodes. The nodes form a tree whose leaves are
3666// regular constants, which themselves are trees that createSpvConstant()
3667// recursively walks. So, this function walks the "top" of the tree:
3668// - emit specialization constant-building instructions for specConstant
3669// - when running into a non-spec-constant, switch to createSpvConstant()
3670spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3671{
3672 assert(node.getQualifier().storage == glslang::EvqConst);
3673
John Kessenich6c292d32016-02-15 20:58:50 -07003674 if (! node.getQualifier().specConstant) {
3675 // hand off to the non-spec-constant path
3676 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3677 int nextConst = 0;
3678 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3679 nextConst, false);
3680 }
3681
3682 // We now know we have a specialization constant to build
3683
3684 if (node.getAsSymbolNode() && node.getQualifier().hasSpecConstantId()) {
3685 // this is a direct literal assigned to a layout(constant_id=) declaration
3686 int nextConst = 0;
3687 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3688 nextConst, true);
3689 } else {
3690 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3691 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3692 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3693 std::vector<spv::Id> dimConstId;
3694 for (int dim = 0; dim < 3; ++dim) {
3695 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3696 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3697 if (specConst)
3698 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3699 }
3700 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3701 } else {
3702 spv::MissingFunctionality("specialization-constant expression trees");
3703 return spv::NoResult;
3704 }
3705 }
John Kessenich55e7d112015-11-15 21:33:39 -07003706}
3707
John Kessenich140f3df2015-06-26 16:58:36 -06003708// Use 'consts' as the flattened glslang source of scalar constants to recursively
3709// build the aggregate SPIR-V constant.
3710//
3711// If there are not enough elements present in 'consts', 0 will be substituted;
3712// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3713//
John Kessenich55e7d112015-11-15 21:33:39 -07003714spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003715{
3716 // vector of constants for SPIR-V
3717 std::vector<spv::Id> spvConsts;
3718
3719 // Type is used for struct and array constants
3720 spv::Id typeId = convertGlslangToSpvType(glslangType);
3721
3722 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003723 glslang::TType elementType(glslangType, 0);
3724 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003725 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003726 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003727 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003728 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003729 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003730 } else if (glslangType.getStruct()) {
3731 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3732 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003733 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003734 } else if (glslangType.isVector()) {
3735 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3736 bool zero = nextConst >= consts.size();
3737 switch (glslangType.getBasicType()) {
3738 case glslang::EbtInt:
3739 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3740 break;
3741 case glslang::EbtUint:
3742 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3743 break;
3744 case glslang::EbtFloat:
3745 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3746 break;
3747 case glslang::EbtDouble:
3748 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3749 break;
3750 case glslang::EbtBool:
3751 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3752 break;
3753 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003754 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003755 break;
3756 }
3757 ++nextConst;
3758 }
3759 } else {
3760 // we have a non-aggregate (scalar) constant
3761 bool zero = nextConst >= consts.size();
3762 spv::Id scalar = 0;
3763 switch (glslangType.getBasicType()) {
3764 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003765 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003766 break;
3767 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003768 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003769 break;
3770 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003771 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003772 break;
3773 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003774 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003775 break;
3776 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003777 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003778 break;
3779 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003780 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003781 break;
3782 }
3783 ++nextConst;
3784 return scalar;
3785 }
3786
3787 return builder.makeCompositeConstant(typeId, spvConsts);
3788}
3789
John Kessenich7c1aa102015-10-15 13:29:11 -06003790// Return true if the node is a constant or symbol whose reading has no
3791// non-trivial observable cost or effect.
3792bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3793{
3794 // don't know what this is
3795 if (node == nullptr)
3796 return false;
3797
3798 // a constant is safe
3799 if (node->getAsConstantUnion() != nullptr)
3800 return true;
3801
3802 // not a symbol means non-trivial
3803 if (node->getAsSymbolNode() == nullptr)
3804 return false;
3805
3806 // a symbol, depends on what's being read
3807 switch (node->getType().getQualifier().storage) {
3808 case glslang::EvqTemporary:
3809 case glslang::EvqGlobal:
3810 case glslang::EvqIn:
3811 case glslang::EvqInOut:
3812 case glslang::EvqConst:
3813 case glslang::EvqConstReadOnly:
3814 case glslang::EvqUniform:
3815 return true;
3816 default:
3817 return false;
3818 }
3819}
3820
3821// A node is trivial if it is a single operation with no side effects.
3822// Error on the side of saying non-trivial.
3823// Return true if trivial.
3824bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3825{
3826 if (node == nullptr)
3827 return false;
3828
3829 // symbols and constants are trivial
3830 if (isTrivialLeaf(node))
3831 return true;
3832
3833 // otherwise, it needs to be a simple operation or one or two leaf nodes
3834
3835 // not a simple operation
3836 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3837 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3838 if (binaryNode == nullptr && unaryNode == nullptr)
3839 return false;
3840
3841 // not on leaf nodes
3842 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3843 return false;
3844
3845 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3846 return false;
3847 }
3848
3849 switch (node->getAsOperator()->getOp()) {
3850 case glslang::EOpLogicalNot:
3851 case glslang::EOpConvIntToBool:
3852 case glslang::EOpConvUintToBool:
3853 case glslang::EOpConvFloatToBool:
3854 case glslang::EOpConvDoubleToBool:
3855 case glslang::EOpEqual:
3856 case glslang::EOpNotEqual:
3857 case glslang::EOpLessThan:
3858 case glslang::EOpGreaterThan:
3859 case glslang::EOpLessThanEqual:
3860 case glslang::EOpGreaterThanEqual:
3861 case glslang::EOpIndexDirect:
3862 case glslang::EOpIndexDirectStruct:
3863 case glslang::EOpLogicalXor:
3864 case glslang::EOpAny:
3865 case glslang::EOpAll:
3866 return true;
3867 default:
3868 return false;
3869 }
3870}
3871
3872// Emit short-circuiting code, where 'right' is never evaluated unless
3873// the left side is true (for &&) or false (for ||).
3874spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3875{
3876 spv::Id boolTypeId = builder.makeBoolType();
3877
3878 // emit left operand
3879 builder.clearAccessChain();
3880 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08003881 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06003882
3883 // Operands to accumulate OpPhi operands
3884 std::vector<spv::Id> phiOperands;
3885 // accumulate left operand's phi information
3886 phiOperands.push_back(leftId);
3887 phiOperands.push_back(builder.getBuildPoint()->getId());
3888
3889 // Make the two kinds of operation symmetric with a "!"
3890 // || => emit "if (! left) result = right"
3891 // && => emit "if ( left) result = right"
3892 //
3893 // TODO: this runtime "not" for || could be avoided by adding functionality
3894 // to 'builder' to have an "else" without an "then"
3895 if (op == glslang::EOpLogicalOr)
3896 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3897
3898 // make an "if" based on the left value
3899 spv::Builder::If ifBuilder(leftId, builder);
3900
3901 // emit right operand as the "then" part of the "if"
3902 builder.clearAccessChain();
3903 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08003904 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06003905
3906 // accumulate left operand's phi information
3907 phiOperands.push_back(rightId);
3908 phiOperands.push_back(builder.getBuildPoint()->getId());
3909
3910 // finish the "if"
3911 ifBuilder.makeEndIf();
3912
3913 // phi together the two results
3914 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3915}
3916
John Kessenich140f3df2015-06-26 16:58:36 -06003917}; // end anonymous namespace
3918
3919namespace glslang {
3920
John Kessenich68d78fd2015-07-12 19:28:10 -06003921void GetSpirvVersion(std::string& version)
3922{
John Kessenich9e55f632015-07-15 10:03:39 -06003923 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003924 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003925 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003926 version = buf;
3927}
3928
John Kessenich140f3df2015-06-26 16:58:36 -06003929// Write SPIR-V out to a binary file
3930void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3931{
3932 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003933 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003934 for (int i = 0; i < (int)spirv.size(); ++i) {
3935 unsigned int word = spirv[i];
3936 out.write((const char*)&word, 4);
3937 }
3938 out.close();
3939}
3940
3941//
3942// Set up the glslang traversal
3943//
3944void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3945{
3946 TIntermNode* root = intermediate.getTreeRoot();
3947
3948 if (root == 0)
3949 return;
3950
3951 glslang::GetThreadPoolAllocator().push();
3952
3953 TGlslangToSpvTraverser it(&intermediate);
3954
3955 root->traverse(&it);
3956
3957 it.dumpSpv(spirv);
3958
3959 glslang::GetThreadPoolAllocator().pop();
3960}
3961
3962}; // end namespace glslang