blob: f3b06530966318ef890ef402dcf5e9f27c996256 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
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//
John Kessenich927608b2017-01-06 12:34:14 -070023// 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.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
Lei Zhang17535f72016-05-04 15:55:59 -0400104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
steve-lunargf1709e72017-05-02 20:14:50 -0600125 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600126 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600127 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
128 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600129 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
130 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
131 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600132 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700133 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600134 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600135 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
136 glslang::TLayoutPacking, const glslang::TQualifier&);
137 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
138 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700139 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700140 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800141 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600142 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700143 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700144 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
145 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
146 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100147 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600148
John Kessenich6fccb3c2016-09-19 16:01:41 -0600149 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600150 void makeFunctions(const glslang::TIntermSequence&);
151 void makeGlobalInitializers(const glslang::TIntermSequence&);
152 void visitFunctions(const glslang::TIntermSequence&);
153 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800154 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600155 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
156 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600157 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
158
qining25262b32016-05-06 17:25:16 -0400159 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
160 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
161 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800162 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800163 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600164 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800165 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800166 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800167 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600168 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800169 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600170 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
171 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700172 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600173 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700174 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400175 spv::Id createSpvConstant(const glslang::TIntermTyped&);
176 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600177 bool isTrivialLeaf(const glslang::TIntermTyped* node);
178 bool isTrivial(const glslang::TIntermTyped* node);
179 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800180 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600181
182 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600183 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700184 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600185 int sequenceDepth;
186
Lei Zhang17535f72016-05-04 15:55:59 -0400187 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400188
John Kessenich140f3df2015-06-26 16:58:36 -0600189 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
190 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700191 bool inEntryPoint;
192 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700193 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 -0700194 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600195 const glslang::TIntermediate* glslangIntermediate;
196 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800197 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600198
John Kessenich2f273362015-07-18 22:34:27 -0600199 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600200 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600201 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700202 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600203 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 -0600204 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600205};
206
207//
208// Helper functions for translating glslang representations to SPIR-V enumerants.
209//
210
211// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700212spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600213{
John Kessenich66e2faf2016-03-12 18:34:36 -0700214 switch (source) {
215 case glslang::EShSourceGlsl:
216 switch (profile) {
217 case ENoProfile:
218 case ECoreProfile:
219 case ECompatibilityProfile:
220 return spv::SourceLanguageGLSL;
221 case EEsProfile:
222 return spv::SourceLanguageESSL;
223 default:
224 return spv::SourceLanguageUnknown;
225 }
226 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600227 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600228 default:
229 return spv::SourceLanguageUnknown;
230 }
231}
232
233// Translate glslang language (stage) to SPIR-V execution model.
234spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
235{
236 switch (stage) {
237 case EShLangVertex: return spv::ExecutionModelVertex;
238 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
239 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
240 case EShLangGeometry: return spv::ExecutionModelGeometry;
241 case EShLangFragment: return spv::ExecutionModelFragment;
242 case EShLangCompute: return spv::ExecutionModelGLCompute;
243 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700244 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600245 return spv::ExecutionModelFragment;
246 }
247}
248
John Kessenich140f3df2015-06-26 16:58:36 -0600249// Translate glslang sampler type to SPIR-V dimensionality.
250spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
251{
252 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700253 case glslang::Esd1D: return spv::Dim1D;
254 case glslang::Esd2D: return spv::Dim2D;
255 case glslang::Esd3D: return spv::Dim3D;
256 case glslang::EsdCube: return spv::DimCube;
257 case glslang::EsdRect: return spv::DimRect;
258 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700259 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600260 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700261 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600262 return spv::Dim2D;
263 }
264}
265
John Kessenichf6640762016-08-01 19:44:00 -0600266// Translate glslang precision to SPIR-V precision decorations.
267spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600268{
John Kessenichf6640762016-08-01 19:44:00 -0600269 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700270 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600271 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600272 default:
273 return spv::NoPrecision;
274 }
275}
276
John Kessenichf6640762016-08-01 19:44:00 -0600277// Translate glslang type to SPIR-V precision decorations.
278spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
279{
280 return TranslatePrecisionDecoration(type.getQualifier().precision);
281}
282
John Kessenich140f3df2015-06-26 16:58:36 -0600283// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600284spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600285{
286 if (type.getBasicType() == glslang::EbtBlock) {
287 switch (type.getQualifier().storage) {
288 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600289 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600290 case glslang::EvqVaryingIn: return spv::DecorationBlock;
291 case glslang::EvqVaryingOut: return spv::DecorationBlock;
292 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700293 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600294 break;
295 }
296 }
297
John Kessenich4016e382016-07-15 11:53:56 -0600298 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600299}
300
Rex Xu1da878f2016-02-21 20:59:01 +0800301// Translate glslang type to SPIR-V memory decorations.
302void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
303{
304 if (qualifier.coherent)
305 memory.push_back(spv::DecorationCoherent);
306 if (qualifier.volatil)
307 memory.push_back(spv::DecorationVolatile);
308 if (qualifier.restrict)
309 memory.push_back(spv::DecorationRestrict);
310 if (qualifier.readonly)
311 memory.push_back(spv::DecorationNonWritable);
312 if (qualifier.writeonly)
313 memory.push_back(spv::DecorationNonReadable);
314}
315
John Kessenich140f3df2015-06-26 16:58:36 -0600316// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700317spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600318{
319 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700320 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600321 case glslang::ElmRowMajor:
322 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700323 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600324 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700325 default:
326 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600327 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600328 }
329 } else {
330 switch (type.getBasicType()) {
331 default:
John Kessenich4016e382016-07-15 11:53:56 -0600332 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600333 break;
334 case glslang::EbtBlock:
335 switch (type.getQualifier().storage) {
336 case glslang::EvqUniform:
337 case glslang::EvqBuffer:
338 switch (type.getQualifier().layoutPacking) {
339 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600340 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
341 default:
John Kessenich4016e382016-07-15 11:53:56 -0600342 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600343 }
344 case glslang::EvqVaryingIn:
345 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700346 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600347 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600348 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700349 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600350 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600351 }
352 }
353 }
354}
355
356// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600357// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700358// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800359spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600360{
Rex Xubbceed72016-05-21 09:40:44 +0800361 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700362 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600363 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800364 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700365 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700366 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600367 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800368#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800369 else if (qualifier.explicitInterp) {
370 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800371 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800372 }
Rex Xu9d93a232016-05-05 12:30:44 +0800373#endif
Rex Xubbceed72016-05-21 09:40:44 +0800374 else
John Kessenich4016e382016-07-15 11:53:56 -0600375 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800376}
377
378// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600379// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800380// should be applied.
381spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
382{
383 if (qualifier.patch)
384 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700385 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600386 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700387 else if (qualifier.sample) {
388 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600389 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700390 } else
John Kessenich4016e382016-07-15 11:53:56 -0600391 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600392}
393
John Kessenich92187592016-02-01 13:45:25 -0700394// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700395spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600396{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700397 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600398 return spv::DecorationInvariant;
399 else
John Kessenich4016e382016-07-15 11:53:56 -0600400 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600401}
402
qining9220dbb2016-05-04 17:34:38 -0400403// If glslang type is noContraction, return SPIR-V NoContraction decoration.
404spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
405{
406 if (qualifier.noContraction)
407 return spv::DecorationNoContraction;
408 else
John Kessenich4016e382016-07-15 11:53:56 -0600409 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400410}
411
David Netoa901ffe2016-06-08 14:11:40 +0100412// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
413// associated capabilities when required. For some built-in variables, a capability
414// is generated only when using the variable in an executable instruction, but not when
415// just declaring a struct member variable with it. This is true for PointSize,
416// ClipDistance, and CullDistance.
417spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600418{
419 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700420 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600421 // Defer adding the capability until the built-in is actually used.
422 if (! memberDeclaration) {
423 switch (glslangIntermediate->getStage()) {
424 case EShLangGeometry:
425 builder.addCapability(spv::CapabilityGeometryPointSize);
426 break;
427 case EShLangTessControl:
428 case EShLangTessEvaluation:
429 builder.addCapability(spv::CapabilityTessellationPointSize);
430 break;
431 default:
432 break;
433 }
John Kessenich92187592016-02-01 13:45:25 -0700434 }
435 return spv::BuiltInPointSize;
436
John Kessenichebb50532016-05-16 19:22:05 -0600437 // These *Distance capabilities logically belong here, but if the member is declared and
438 // then never used, consumers of SPIR-V prefer the capability not be declared.
439 // They are now generated when used, rather than here when declared.
440 // Potentially, the specification should be more clear what the minimum
441 // use needed is to trigger the capability.
442 //
John Kessenich92187592016-02-01 13:45:25 -0700443 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100444 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800445 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700446 return spv::BuiltInClipDistance;
447
448 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100449 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800450 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700451 return spv::BuiltInCullDistance;
452
453 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800454 if (!memberDeclaration) {
455 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800456#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800457 if (glslangIntermediate->getStage() == EShLangVertex ||
458 glslangIntermediate->getStage() == EShLangTessControl ||
459 glslangIntermediate->getStage() == EShLangTessEvaluation) {
460
461 builder.addExtension(spv::E_SPV_NV_viewport_array2);
462 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
463 }
chaoc771d89f2017-01-13 01:10:53 -0800464#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800465 }
John Kessenich92187592016-02-01 13:45:25 -0700466 return spv::BuiltInViewportIndex;
467
John Kessenich5e801132016-02-15 11:09:46 -0700468 case glslang::EbvSampleId:
469 builder.addCapability(spv::CapabilitySampleRateShading);
470 return spv::BuiltInSampleId;
471
472 case glslang::EbvSamplePosition:
473 builder.addCapability(spv::CapabilitySampleRateShading);
474 return spv::BuiltInSamplePosition;
475
476 case glslang::EbvSampleMask:
477 builder.addCapability(spv::CapabilitySampleRateShading);
478 return spv::BuiltInSampleMask;
479
John Kessenich78a45572016-07-08 14:05:15 -0600480 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800481 if (!memberDeclaration) {
482 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800483#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800484 if (glslangIntermediate->getStage() == EShLangVertex ||
485 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800486 glslangIntermediate->getStage() == EShLangTessEvaluation) {
487
chaoc771d89f2017-01-13 01:10:53 -0800488 builder.addExtension(spv::E_SPV_NV_viewport_array2);
489 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
490 }
chaoc771d89f2017-01-13 01:10:53 -0800491#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800492 }
493
John Kessenich78a45572016-07-08 14:05:15 -0600494 return spv::BuiltInLayer;
495
John Kessenich140f3df2015-06-26 16:58:36 -0600496 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600497 case glslang::EbvVertexId: return spv::BuiltInVertexId;
498 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700499 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
500 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800501
John Kessenichda581a22015-10-14 14:10:30 -0600502 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800503 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
504 builder.addCapability(spv::CapabilityDrawParameters);
505 return spv::BuiltInBaseVertex;
506
John Kessenichda581a22015-10-14 14:10:30 -0600507 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800508 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
509 builder.addCapability(spv::CapabilityDrawParameters);
510 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200511
John Kessenichda581a22015-10-14 14:10:30 -0600512 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800513 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
514 builder.addCapability(spv::CapabilityDrawParameters);
515 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200516
517 case glslang::EbvPrimitiveId:
518 if (glslangIntermediate->getStage() == EShLangFragment)
519 builder.addCapability(spv::CapabilityGeometry);
520 return spv::BuiltInPrimitiveId;
521
John Kessenich140f3df2015-06-26 16:58:36 -0600522 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600523 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
524 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
525 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
526 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
527 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
528 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
529 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600530 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
531 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
532 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
533 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
534 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
535 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
536 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
537 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800538
Rex Xu574ab042016-04-14 16:53:07 +0800539 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800540 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800541 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
542 return spv::BuiltInSubgroupSize;
543
Rex Xu574ab042016-04-14 16:53:07 +0800544 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800545 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800546 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
547 return spv::BuiltInSubgroupLocalInvocationId;
548
Rex Xu574ab042016-04-14 16:53:07 +0800549 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800550 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
551 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
552 return spv::BuiltInSubgroupEqMaskKHR;
553
Rex Xu574ab042016-04-14 16:53:07 +0800554 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800555 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
556 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
557 return spv::BuiltInSubgroupGeMaskKHR;
558
Rex Xu574ab042016-04-14 16:53:07 +0800559 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800560 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
561 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
562 return spv::BuiltInSubgroupGtMaskKHR;
563
Rex Xu574ab042016-04-14 16:53:07 +0800564 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800565 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
566 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
567 return spv::BuiltInSubgroupLeMaskKHR;
568
Rex Xu574ab042016-04-14 16:53:07 +0800569 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800570 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
571 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
572 return spv::BuiltInSubgroupLtMaskKHR;
573
Rex Xu9d93a232016-05-05 12:30:44 +0800574#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800575 case glslang::EbvBaryCoordNoPersp:
576 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
577 return spv::BuiltInBaryCoordNoPerspAMD;
578
579 case glslang::EbvBaryCoordNoPerspCentroid:
580 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
581 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
582
583 case glslang::EbvBaryCoordNoPerspSample:
584 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
585 return spv::BuiltInBaryCoordNoPerspSampleAMD;
586
587 case glslang::EbvBaryCoordSmooth:
588 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
589 return spv::BuiltInBaryCoordSmoothAMD;
590
591 case glslang::EbvBaryCoordSmoothCentroid:
592 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
593 return spv::BuiltInBaryCoordSmoothCentroidAMD;
594
595 case glslang::EbvBaryCoordSmoothSample:
596 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
597 return spv::BuiltInBaryCoordSmoothSampleAMD;
598
599 case glslang::EbvBaryCoordPullModel:
600 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
601 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800602#endif
chaoc771d89f2017-01-13 01:10:53 -0800603
John Kessenich6c8aaac2017-02-27 01:20:51 -0700604 case glslang::EbvDeviceIndex:
605 builder.addExtension(spv::E_SPV_KHR_device_group);
606 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700607 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700608
609 case glslang::EbvViewIndex:
610 builder.addExtension(spv::E_SPV_KHR_multiview);
611 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700612 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700613
chaoc771d89f2017-01-13 01:10:53 -0800614#ifdef NV_EXTENSIONS
615 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800616 if (!memberDeclaration) {
617 builder.addExtension(spv::E_SPV_NV_viewport_array2);
618 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
619 }
chaoc771d89f2017-01-13 01:10:53 -0800620 return spv::BuiltInViewportMaskNV;
621 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800622 if (!memberDeclaration) {
623 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
624 builder.addCapability(spv::CapabilityShaderStereoViewNV);
625 }
chaoc771d89f2017-01-13 01:10:53 -0800626 return spv::BuiltInSecondaryPositionNV;
627 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800628 if (!memberDeclaration) {
629 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
630 builder.addCapability(spv::CapabilityShaderStereoViewNV);
631 }
chaoc771d89f2017-01-13 01:10:53 -0800632 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800633 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800634 if (!memberDeclaration) {
635 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
636 builder.addCapability(spv::CapabilityPerViewAttributesNV);
637 }
chaocdf3956c2017-02-14 14:52:34 -0800638 return spv::BuiltInPositionPerViewNV;
639 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800640 if (!memberDeclaration) {
641 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
642 builder.addCapability(spv::CapabilityPerViewAttributesNV);
643 }
chaocdf3956c2017-02-14 14:52:34 -0800644 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800645#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800646 default:
647 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600648 }
649}
650
Rex Xufc618912015-09-09 16:42:49 +0800651// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700652spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800653{
654 assert(type.getBasicType() == glslang::EbtSampler);
655
John Kessenich5d0fa972016-02-15 11:57:00 -0700656 // Check for capabilities
657 switch (type.getQualifier().layoutFormat) {
658 case glslang::ElfRg32f:
659 case glslang::ElfRg16f:
660 case glslang::ElfR11fG11fB10f:
661 case glslang::ElfR16f:
662 case glslang::ElfRgba16:
663 case glslang::ElfRgb10A2:
664 case glslang::ElfRg16:
665 case glslang::ElfRg8:
666 case glslang::ElfR16:
667 case glslang::ElfR8:
668 case glslang::ElfRgba16Snorm:
669 case glslang::ElfRg16Snorm:
670 case glslang::ElfRg8Snorm:
671 case glslang::ElfR16Snorm:
672 case glslang::ElfR8Snorm:
673
674 case glslang::ElfRg32i:
675 case glslang::ElfRg16i:
676 case glslang::ElfRg8i:
677 case glslang::ElfR16i:
678 case glslang::ElfR8i:
679
680 case glslang::ElfRgb10a2ui:
681 case glslang::ElfRg32ui:
682 case glslang::ElfRg16ui:
683 case glslang::ElfRg8ui:
684 case glslang::ElfR16ui:
685 case glslang::ElfR8ui:
686 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
687 break;
688
689 default:
690 break;
691 }
692
693 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800694 switch (type.getQualifier().layoutFormat) {
695 case glslang::ElfNone: return spv::ImageFormatUnknown;
696 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
697 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
698 case glslang::ElfR32f: return spv::ImageFormatR32f;
699 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
700 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
701 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
702 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
703 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
704 case glslang::ElfR16f: return spv::ImageFormatR16f;
705 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
706 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
707 case glslang::ElfRg16: return spv::ImageFormatRg16;
708 case glslang::ElfRg8: return spv::ImageFormatRg8;
709 case glslang::ElfR16: return spv::ImageFormatR16;
710 case glslang::ElfR8: return spv::ImageFormatR8;
711 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
712 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
713 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
714 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
715 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
716 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
717 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
718 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
719 case glslang::ElfR32i: return spv::ImageFormatR32i;
720 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
721 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
722 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
723 case glslang::ElfR16i: return spv::ImageFormatR16i;
724 case glslang::ElfR8i: return spv::ImageFormatR8i;
725 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
726 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
727 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
728 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
729 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
730 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
731 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
732 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
733 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
734 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600735 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800736 }
737}
738
steve-lunargf1709e72017-05-02 20:14:50 -0600739spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
740{
741 switch (loopControl) {
742 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
743 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
744 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
745 // TODO: DependencyInfinite
746 // TODO: DependencyLength
747 default: return spv::LoopControlMaskNone;
748 }
749}
750
John Kessenicha5c5fb62017-05-05 05:09:58 -0600751// Translate glslang type to SPIR-V storage class.
752spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
753{
754 if (type.getQualifier().isPipeInput())
755 return spv::StorageClassInput;
756 else if (type.getQualifier().isPipeOutput())
757 return spv::StorageClassOutput;
758 else if (type.getBasicType() == glslang::EbtAtomicUint)
759 return spv::StorageClassAtomicCounter;
760 else if (type.containsOpaque())
761 return spv::StorageClassUniformConstant;
762 else if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
763 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
764 return spv::StorageClassStorageBuffer;
765 } else if (type.getQualifier().isUniformOrBuffer()) {
766 if (type.getQualifier().layoutPushConstant)
767 return spv::StorageClassPushConstant;
768 if (type.getBasicType() == glslang::EbtBlock)
769 return spv::StorageClassUniform;
770 else
771 return spv::StorageClassUniformConstant;
772 } else {
773 switch (type.getQualifier().storage) {
774 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
775 case glslang::EvqGlobal: return spv::StorageClassPrivate;
776 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
777 case glslang::EvqTemporary: return spv::StorageClassFunction;
778 default:
779 assert(0);
780 return spv::StorageClassFunction;
781 }
782 }
783}
784
qining25262b32016-05-06 17:25:16 -0400785// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700786// descriptor set.
787bool IsDescriptorResource(const glslang::TType& type)
788{
John Kessenichf7497e22016-03-08 21:36:22 -0700789 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700790 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700791 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700792
793 // non block...
794 // basically samplerXXX/subpass/sampler/texture are all included
795 // if they are the global-scope-class, not the function parameter
796 // (or local, if they ever exist) class.
797 if (type.getBasicType() == glslang::EbtSampler)
798 return type.getQualifier().isUniformOrBuffer();
799
800 // None of the above.
801 return false;
802}
803
John Kesseniche0b6cad2015-12-24 10:30:13 -0700804void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
805{
806 if (child.layoutMatrix == glslang::ElmNone)
807 child.layoutMatrix = parent.layoutMatrix;
808
809 if (parent.invariant)
810 child.invariant = true;
811 if (parent.nopersp)
812 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800813#ifdef AMD_EXTENSIONS
814 if (parent.explicitInterp)
815 child.explicitInterp = true;
816#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700817 if (parent.flat)
818 child.flat = true;
819 if (parent.centroid)
820 child.centroid = true;
821 if (parent.patch)
822 child.patch = true;
823 if (parent.sample)
824 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800825 if (parent.coherent)
826 child.coherent = true;
827 if (parent.volatil)
828 child.volatil = true;
829 if (parent.restrict)
830 child.restrict = true;
831 if (parent.readonly)
832 child.readonly = true;
833 if (parent.writeonly)
834 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700835}
836
John Kessenichf2b7f332016-09-01 17:05:23 -0600837bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700838{
John Kessenich7b9fa252016-01-21 18:56:57 -0700839 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600840 // - struct members might inherit from a struct declaration
841 // (note that non-block structs don't explicitly inherit,
842 // only implicitly, meaning no decoration involved)
843 // - affect decorations on the struct members
844 // (note smooth does not, and expecting something like volatile
845 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700846 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600847 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700848}
849
John Kessenich140f3df2015-06-26 16:58:36 -0600850//
851// Implement the TGlslangToSpvTraverser class.
852//
853
Lei Zhang17535f72016-05-04 15:55:59 -0400854TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600855 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
856 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400857 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700858 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600859 glslangIntermediate(glslangIntermediate)
860{
861 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
862
863 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700864 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600865 stdBuiltins = builder.import("GLSL.std.450");
866 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600867 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
868 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600869
870 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600871 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
872 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600873 builder.addSourceExtension(it->c_str());
874
875 // Add the top-level modes for this shader.
876
John Kessenich92187592016-02-01 13:45:25 -0700877 if (glslangIntermediate->getXfbMode()) {
878 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600879 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700880 }
John Kessenich140f3df2015-06-26 16:58:36 -0600881
882 unsigned int mode;
883 switch (glslangIntermediate->getStage()) {
884 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600885 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600886 break;
887
steve-lunarge7412492017-03-23 11:56:07 -0600888 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600889 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600890 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600891
steve-lunarge7412492017-03-23 11:56:07 -0600892 glslang::TLayoutGeometry primitive;
893
894 if (glslangIntermediate->getStage() == EShLangTessControl) {
895 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
896 primitive = glslangIntermediate->getOutputPrimitive();
897 } else {
898 primitive = glslangIntermediate->getInputPrimitive();
899 }
900
901 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700902 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
903 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
904 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600905 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600906 }
John Kessenich4016e382016-07-15 11:53:56 -0600907 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600908 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
909
John Kesseniche6903322015-10-13 16:29:02 -0600910 switch (glslangIntermediate->getVertexSpacing()) {
911 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
912 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
913 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600914 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600915 }
John Kessenich4016e382016-07-15 11:53:56 -0600916 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600917 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
918
919 switch (glslangIntermediate->getVertexOrder()) {
920 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
921 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600922 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600923 }
John Kessenich4016e382016-07-15 11:53:56 -0600924 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600925 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
926
927 if (glslangIntermediate->getPointMode())
928 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600929 break;
930
931 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600932 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600933 switch (glslangIntermediate->getInputPrimitive()) {
934 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
935 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
936 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700937 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600938 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600939 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600940 }
John Kessenich4016e382016-07-15 11:53:56 -0600941 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600942 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600943
John Kessenich140f3df2015-06-26 16:58:36 -0600944 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
945
946 switch (glslangIntermediate->getOutputPrimitive()) {
947 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
948 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
949 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600950 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600951 }
John Kessenich4016e382016-07-15 11:53:56 -0600952 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600953 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
954 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
955 break;
956
957 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600958 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600959 if (glslangIntermediate->getPixelCenterInteger())
960 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600961
John Kessenich140f3df2015-06-26 16:58:36 -0600962 if (glslangIntermediate->getOriginUpperLeft())
963 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600964 else
965 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600966
967 if (glslangIntermediate->getEarlyFragmentTests())
968 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
969
970 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600971 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
972 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600973 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600974 }
John Kessenich4016e382016-07-15 11:53:56 -0600975 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600976 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
977
978 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
979 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600980 break;
981
982 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600983 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600984 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
985 glslangIntermediate->getLocalSize(1),
986 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600987 break;
988
989 default:
990 break;
991 }
John Kessenich140f3df2015-06-26 16:58:36 -0600992}
993
John Kessenichfca82622016-11-26 13:23:20 -0700994// Finish creating SPV, after the traversal is complete.
995void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700996{
John Kessenich517fe7a2016-11-26 13:31:47 -0700997 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700998 builder.setBuildPoint(shaderEntry->getLastBlock());
999 builder.leaveFunction();
1000 }
1001
John Kessenich7ba63412015-12-20 17:37:07 -07001002 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001003 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1004 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001005
qiningda397332016-03-09 19:54:03 -05001006 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001007}
1008
John Kessenichfca82622016-11-26 13:23:20 -07001009// Write the SPV into 'out'.
1010void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001011{
John Kessenichfca82622016-11-26 13:23:20 -07001012 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001013}
1014
1015//
1016// Implement the traversal functions.
1017//
1018// Return true from interior nodes to have the external traversal
1019// continue on to children. Return false if children were
1020// already processed.
1021//
1022
1023//
qining25262b32016-05-06 17:25:16 -04001024// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001025// - uniform/input reads
1026// - output writes
1027// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1028// - something simple that degenerates into the last bullet
1029//
1030void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1031{
qining75d1d802016-04-06 14:42:01 -04001032 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1033 if (symbol->getType().getQualifier().isSpecConstant())
1034 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1035
John Kessenich140f3df2015-06-26 16:58:36 -06001036 // getSymbolId() will set up all the IO decorations on the first call.
1037 // Formal function parameters were mapped during makeFunctions().
1038 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001039
1040 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1041 if (builder.isPointer(id)) {
1042 spv::StorageClass sc = builder.getStorageClass(id);
1043 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1044 iOSet.insert(id);
1045 }
1046
1047 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001048 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001049 // Prepare to generate code for the access
1050
1051 // L-value chains will be computed left to right. We're on the symbol now,
1052 // which is the left-most part of the access chain, so now is "clear" time,
1053 // followed by setting the base.
1054 builder.clearAccessChain();
1055
1056 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001057 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001058 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001059 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001060 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001061 // These are also pure R-values.
1062 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001063 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001064 builder.setAccessChainRValue(id);
1065 else
1066 builder.setAccessChainLValue(id);
1067 }
1068}
1069
1070bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1071{
qining40887662016-04-03 22:20:42 -04001072 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1073 if (node->getType().getQualifier().isSpecConstant())
1074 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1075
John Kessenich140f3df2015-06-26 16:58:36 -06001076 // First, handle special cases
1077 switch (node->getOp()) {
1078 case glslang::EOpAssign:
1079 case glslang::EOpAddAssign:
1080 case glslang::EOpSubAssign:
1081 case glslang::EOpMulAssign:
1082 case glslang::EOpVectorTimesMatrixAssign:
1083 case glslang::EOpVectorTimesScalarAssign:
1084 case glslang::EOpMatrixTimesScalarAssign:
1085 case glslang::EOpMatrixTimesMatrixAssign:
1086 case glslang::EOpDivAssign:
1087 case glslang::EOpModAssign:
1088 case glslang::EOpAndAssign:
1089 case glslang::EOpInclusiveOrAssign:
1090 case glslang::EOpExclusiveOrAssign:
1091 case glslang::EOpLeftShiftAssign:
1092 case glslang::EOpRightShiftAssign:
1093 // A bin-op assign "a += b" means the same thing as "a = a + b"
1094 // where a is evaluated before b. For a simple assignment, GLSL
1095 // says to evaluate the left before the right. So, always, left
1096 // node then right node.
1097 {
1098 // get the left l-value, save it away
1099 builder.clearAccessChain();
1100 node->getLeft()->traverse(this);
1101 spv::Builder::AccessChain lValue = builder.getAccessChain();
1102
1103 // evaluate the right
1104 builder.clearAccessChain();
1105 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001106 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001107
1108 if (node->getOp() != glslang::EOpAssign) {
1109 // the left is also an r-value
1110 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001111 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001112
1113 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001114 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001115 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001116 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1117 node->getType().getBasicType());
1118
1119 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001120 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001121 }
1122
1123 // store the result
1124 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001125 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001126
1127 // assignments are expressions having an rValue after they are evaluated...
1128 builder.clearAccessChain();
1129 builder.setAccessChainRValue(rValue);
1130 }
1131 return false;
1132 case glslang::EOpIndexDirect:
1133 case glslang::EOpIndexDirectStruct:
1134 {
1135 // Get the left part of the access chain.
1136 node->getLeft()->traverse(this);
1137
1138 // Add the next element in the chain
1139
David Netoa901ffe2016-06-08 14:11:40 +01001140 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001141 if (! node->getLeft()->getType().isArray() &&
1142 node->getLeft()->getType().isVector() &&
1143 node->getOp() == glslang::EOpIndexDirect) {
1144 // This is essentially a hard-coded vector swizzle of size 1,
1145 // so short circuit the access-chain stuff with a swizzle.
1146 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001147 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001148 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001149 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001150 int spvIndex = glslangIndex;
1151 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1152 node->getOp() == glslang::EOpIndexDirectStruct)
1153 {
1154 // This may be, e.g., an anonymous block-member selection, which generally need
1155 // index remapping due to hidden members in anonymous blocks.
1156 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1157 assert(remapper.size() > 0);
1158 spvIndex = remapper[glslangIndex];
1159 }
John Kessenichebb50532016-05-16 19:22:05 -06001160
David Netoa901ffe2016-06-08 14:11:40 +01001161 // normal case for indexing array or structure or block
1162 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1163
1164 // Add capabilities here for accessing PointSize and clip/cull distance.
1165 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001166 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001167 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001168 }
1169 }
1170 return false;
1171 case glslang::EOpIndexIndirect:
1172 {
1173 // Structure or array or vector indirection.
1174 // Will use native SPIR-V access-chain for struct and array indirection;
1175 // matrices are arrays of vectors, so will also work for a matrix.
1176 // Will use the access chain's 'component' for variable index into a vector.
1177
1178 // This adapter is building access chains left to right.
1179 // Set up the access chain to the left.
1180 node->getLeft()->traverse(this);
1181
1182 // save it so that computing the right side doesn't trash it
1183 spv::Builder::AccessChain partial = builder.getAccessChain();
1184
1185 // compute the next index in the chain
1186 builder.clearAccessChain();
1187 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001188 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001189
1190 // restore the saved access chain
1191 builder.setAccessChain(partial);
1192
1193 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001194 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001195 else
John Kessenichfa668da2015-09-13 14:46:30 -06001196 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001197 }
1198 return false;
1199 case glslang::EOpVectorSwizzle:
1200 {
1201 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001202 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001203 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001204 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001205 }
1206 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001207 case glslang::EOpMatrixSwizzle:
1208 logger->missingFunctionality("matrix swizzle");
1209 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001210 case glslang::EOpLogicalOr:
1211 case glslang::EOpLogicalAnd:
1212 {
1213
1214 // These may require short circuiting, but can sometimes be done as straight
1215 // binary operations. The right operand must be short circuited if it has
1216 // side effects, and should probably be if it is complex.
1217 if (isTrivial(node->getRight()->getAsTyped()))
1218 break; // handle below as a normal binary operation
1219 // otherwise, we need to do dynamic short circuiting on the right operand
1220 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1221 builder.clearAccessChain();
1222 builder.setAccessChainRValue(result);
1223 }
1224 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001225 default:
1226 break;
1227 }
1228
1229 // Assume generic binary op...
1230
John Kessenich32cfd492016-02-02 12:37:46 -07001231 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001232 builder.clearAccessChain();
1233 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001234 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001235
John Kessenich32cfd492016-02-02 12:37:46 -07001236 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001237 builder.clearAccessChain();
1238 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001239 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001240
John Kessenich32cfd492016-02-02 12:37:46 -07001241 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001242 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001243 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001244 convertGlslangToSpvType(node->getType()), left, right,
1245 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001246
John Kessenich50e57562015-12-21 21:21:11 -07001247 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001248 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001249 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001250 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001251 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001252 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001253 return false;
1254 }
John Kessenich140f3df2015-06-26 16:58:36 -06001255}
1256
1257bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1258{
qining40887662016-04-03 22:20:42 -04001259 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1260 if (node->getType().getQualifier().isSpecConstant())
1261 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1262
John Kessenichfc51d282015-08-19 13:34:18 -06001263 spv::Id result = spv::NoResult;
1264
1265 // try texturing first
1266 result = createImageTextureFunctionCall(node);
1267 if (result != spv::NoResult) {
1268 builder.clearAccessChain();
1269 builder.setAccessChainRValue(result);
1270
1271 return false; // done with this node
1272 }
1273
1274 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001275
1276 if (node->getOp() == glslang::EOpArrayLength) {
1277 // Quite special; won't want to evaluate the operand.
1278
1279 // Normal .length() would have been constant folded by the front-end.
1280 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001281 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001282 assert(node->getOperand()->getType().isRuntimeSizedArray());
1283 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1284 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001285 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1286 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001287
1288 builder.clearAccessChain();
1289 builder.setAccessChainRValue(length);
1290
1291 return false;
1292 }
1293
John Kessenichfc51d282015-08-19 13:34:18 -06001294 // Start by evaluating the operand
1295
John Kessenich8c8505c2016-07-26 12:50:38 -06001296 // Does it need a swizzle inversion? If so, evaluation is inverted;
1297 // operate first on the swizzle base, then apply the swizzle.
1298 spv::Id invertedType = spv::NoType;
1299 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1300 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1301 invertedType = getInvertedSwizzleType(*node->getOperand());
1302
John Kessenich140f3df2015-06-26 16:58:36 -06001303 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001304 if (invertedType != spv::NoType)
1305 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1306 else
1307 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001308
Rex Xufc618912015-09-09 16:42:49 +08001309 spv::Id operand = spv::NoResult;
1310
1311 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1312 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001313 node->getOp() == glslang::EOpAtomicCounter ||
1314 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001315 operand = builder.accessChainGetLValue(); // Special case l-value operands
1316 else
John Kessenich32cfd492016-02-02 12:37:46 -07001317 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001318
John Kessenichf6640762016-08-01 19:44:00 -06001319 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001320 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001321
1322 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001323 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001324 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001325
1326 // if not, then possibly an operation
1327 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001328 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001329
1330 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001331 if (invertedType)
1332 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1333
John Kessenich140f3df2015-06-26 16:58:36 -06001334 builder.clearAccessChain();
1335 builder.setAccessChainRValue(result);
1336
1337 return false; // done with this node
1338 }
1339
1340 // it must be a special case, check...
1341 switch (node->getOp()) {
1342 case glslang::EOpPostIncrement:
1343 case glslang::EOpPostDecrement:
1344 case glslang::EOpPreIncrement:
1345 case glslang::EOpPreDecrement:
1346 {
1347 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001348 spv::Id one = 0;
1349 if (node->getBasicType() == glslang::EbtFloat)
1350 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001351 else if (node->getBasicType() == glslang::EbtDouble)
1352 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001353#ifdef AMD_EXTENSIONS
1354 else if (node->getBasicType() == glslang::EbtFloat16)
1355 one = builder.makeFloat16Constant(1.0F);
1356#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001357 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1358 one = builder.makeInt64Constant(1);
1359 else
1360 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001361 glslang::TOperator op;
1362 if (node->getOp() == glslang::EOpPreIncrement ||
1363 node->getOp() == glslang::EOpPostIncrement)
1364 op = glslang::EOpAdd;
1365 else
1366 op = glslang::EOpSub;
1367
John Kessenichf6640762016-08-01 19:44:00 -06001368 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001369 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001370 convertGlslangToSpvType(node->getType()), operand, one,
1371 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001372 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001373
1374 // The result of operation is always stored, but conditionally the
1375 // consumed result. The consumed result is always an r-value.
1376 builder.accessChainStore(result);
1377 builder.clearAccessChain();
1378 if (node->getOp() == glslang::EOpPreIncrement ||
1379 node->getOp() == glslang::EOpPreDecrement)
1380 builder.setAccessChainRValue(result);
1381 else
1382 builder.setAccessChainRValue(operand);
1383 }
1384
1385 return false;
1386
1387 case glslang::EOpEmitStreamVertex:
1388 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1389 return false;
1390 case glslang::EOpEndStreamPrimitive:
1391 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1392 return false;
1393
1394 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001395 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001396 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001397 }
John Kessenich140f3df2015-06-26 16:58:36 -06001398}
1399
1400bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1401{
qining27e04a02016-04-14 16:40:20 -04001402 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1403 if (node->getType().getQualifier().isSpecConstant())
1404 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1405
John Kessenichfc51d282015-08-19 13:34:18 -06001406 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001407 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1408 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001409
1410 // try texturing
1411 result = createImageTextureFunctionCall(node);
1412 if (result != spv::NoResult) {
1413 builder.clearAccessChain();
1414 builder.setAccessChainRValue(result);
1415
1416 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001417 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001418 // "imageStore" is a special case, which has no result
1419 return false;
1420 }
John Kessenichfc51d282015-08-19 13:34:18 -06001421
John Kessenich140f3df2015-06-26 16:58:36 -06001422 glslang::TOperator binOp = glslang::EOpNull;
1423 bool reduceComparison = true;
1424 bool isMatrix = false;
1425 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001426 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001427
1428 assert(node->getOp());
1429
John Kessenichf6640762016-08-01 19:44:00 -06001430 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001431
1432 switch (node->getOp()) {
1433 case glslang::EOpSequence:
1434 {
1435 if (preVisit)
1436 ++sequenceDepth;
1437 else
1438 --sequenceDepth;
1439
1440 if (sequenceDepth == 1) {
1441 // If this is the parent node of all the functions, we want to see them
1442 // early, so all call points have actual SPIR-V functions to reference.
1443 // In all cases, still let the traverser visit the children for us.
1444 makeFunctions(node->getAsAggregate()->getSequence());
1445
John Kessenich6fccb3c2016-09-19 16:01:41 -06001446 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001447 // anything else gets there, so visit out of order, doing them all now.
1448 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1449
John Kessenich6a60c2f2016-12-08 21:01:59 -07001450 // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
John Kessenich140f3df2015-06-26 16:58:36 -06001451 // so do them manually.
1452 visitFunctions(node->getAsAggregate()->getSequence());
1453
1454 return false;
1455 }
1456
1457 return true;
1458 }
1459 case glslang::EOpLinkerObjects:
1460 {
1461 if (visit == glslang::EvPreVisit)
1462 linkageOnly = true;
1463 else
1464 linkageOnly = false;
1465
1466 return true;
1467 }
1468 case glslang::EOpComma:
1469 {
1470 // processing from left to right naturally leaves the right-most
1471 // lying around in the access chain
1472 glslang::TIntermSequence& glslangOperands = node->getSequence();
1473 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1474 glslangOperands[i]->traverse(this);
1475
1476 return false;
1477 }
1478 case glslang::EOpFunction:
1479 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001480 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001481 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001482 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001483 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001484 } else {
1485 handleFunctionEntry(node);
1486 }
1487 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001488 if (inEntryPoint)
1489 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001490 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001491 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001492 }
1493
1494 return true;
1495 case glslang::EOpParameters:
1496 // Parameters will have been consumed by EOpFunction processing, but not
1497 // the body, so we still visited the function node's children, making this
1498 // child redundant.
1499 return false;
1500 case glslang::EOpFunctionCall:
1501 {
1502 if (node->isUserDefined())
1503 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001504 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07001505 if (result) {
1506 builder.clearAccessChain();
1507 builder.setAccessChainRValue(result);
1508 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001509 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001510
1511 return false;
1512 }
1513 case glslang::EOpConstructMat2x2:
1514 case glslang::EOpConstructMat2x3:
1515 case glslang::EOpConstructMat2x4:
1516 case glslang::EOpConstructMat3x2:
1517 case glslang::EOpConstructMat3x3:
1518 case glslang::EOpConstructMat3x4:
1519 case glslang::EOpConstructMat4x2:
1520 case glslang::EOpConstructMat4x3:
1521 case glslang::EOpConstructMat4x4:
1522 case glslang::EOpConstructDMat2x2:
1523 case glslang::EOpConstructDMat2x3:
1524 case glslang::EOpConstructDMat2x4:
1525 case glslang::EOpConstructDMat3x2:
1526 case glslang::EOpConstructDMat3x3:
1527 case glslang::EOpConstructDMat3x4:
1528 case glslang::EOpConstructDMat4x2:
1529 case glslang::EOpConstructDMat4x3:
1530 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001531 case glslang::EOpConstructIMat2x2:
1532 case glslang::EOpConstructIMat2x3:
1533 case glslang::EOpConstructIMat2x4:
1534 case glslang::EOpConstructIMat3x2:
1535 case glslang::EOpConstructIMat3x3:
1536 case glslang::EOpConstructIMat3x4:
1537 case glslang::EOpConstructIMat4x2:
1538 case glslang::EOpConstructIMat4x3:
1539 case glslang::EOpConstructIMat4x4:
1540 case glslang::EOpConstructUMat2x2:
1541 case glslang::EOpConstructUMat2x3:
1542 case glslang::EOpConstructUMat2x4:
1543 case glslang::EOpConstructUMat3x2:
1544 case glslang::EOpConstructUMat3x3:
1545 case glslang::EOpConstructUMat3x4:
1546 case glslang::EOpConstructUMat4x2:
1547 case glslang::EOpConstructUMat4x3:
1548 case glslang::EOpConstructUMat4x4:
1549 case glslang::EOpConstructBMat2x2:
1550 case glslang::EOpConstructBMat2x3:
1551 case glslang::EOpConstructBMat2x4:
1552 case glslang::EOpConstructBMat3x2:
1553 case glslang::EOpConstructBMat3x3:
1554 case glslang::EOpConstructBMat3x4:
1555 case glslang::EOpConstructBMat4x2:
1556 case glslang::EOpConstructBMat4x3:
1557 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001558#ifdef AMD_EXTENSIONS
1559 case glslang::EOpConstructF16Mat2x2:
1560 case glslang::EOpConstructF16Mat2x3:
1561 case glslang::EOpConstructF16Mat2x4:
1562 case glslang::EOpConstructF16Mat3x2:
1563 case glslang::EOpConstructF16Mat3x3:
1564 case glslang::EOpConstructF16Mat3x4:
1565 case glslang::EOpConstructF16Mat4x2:
1566 case glslang::EOpConstructF16Mat4x3:
1567 case glslang::EOpConstructF16Mat4x4:
1568#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001569 isMatrix = true;
1570 // fall through
1571 case glslang::EOpConstructFloat:
1572 case glslang::EOpConstructVec2:
1573 case glslang::EOpConstructVec3:
1574 case glslang::EOpConstructVec4:
1575 case glslang::EOpConstructDouble:
1576 case glslang::EOpConstructDVec2:
1577 case glslang::EOpConstructDVec3:
1578 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001579#ifdef AMD_EXTENSIONS
1580 case glslang::EOpConstructFloat16:
1581 case glslang::EOpConstructF16Vec2:
1582 case glslang::EOpConstructF16Vec3:
1583 case glslang::EOpConstructF16Vec4:
1584#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001585 case glslang::EOpConstructBool:
1586 case glslang::EOpConstructBVec2:
1587 case glslang::EOpConstructBVec3:
1588 case glslang::EOpConstructBVec4:
1589 case glslang::EOpConstructInt:
1590 case glslang::EOpConstructIVec2:
1591 case glslang::EOpConstructIVec3:
1592 case glslang::EOpConstructIVec4:
1593 case glslang::EOpConstructUint:
1594 case glslang::EOpConstructUVec2:
1595 case glslang::EOpConstructUVec3:
1596 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001597 case glslang::EOpConstructInt64:
1598 case glslang::EOpConstructI64Vec2:
1599 case glslang::EOpConstructI64Vec3:
1600 case glslang::EOpConstructI64Vec4:
1601 case glslang::EOpConstructUint64:
1602 case glslang::EOpConstructU64Vec2:
1603 case glslang::EOpConstructU64Vec3:
1604 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001605 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001606 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001607 {
1608 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001609 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001610 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001611 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001612 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001613 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001614 std::vector<spv::Id> constituents;
1615 for (int c = 0; c < (int)arguments.size(); ++c)
1616 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001617 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001618 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001619 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001620 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001621 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001622
1623 builder.clearAccessChain();
1624 builder.setAccessChainRValue(constructed);
1625
1626 return false;
1627 }
1628
1629 // These six are component-wise compares with component-wise results.
1630 // Forward on to createBinaryOperation(), requesting a vector result.
1631 case glslang::EOpLessThan:
1632 case glslang::EOpGreaterThan:
1633 case glslang::EOpLessThanEqual:
1634 case glslang::EOpGreaterThanEqual:
1635 case glslang::EOpVectorEqual:
1636 case glslang::EOpVectorNotEqual:
1637 {
1638 // Map the operation to a binary
1639 binOp = node->getOp();
1640 reduceComparison = false;
1641 switch (node->getOp()) {
1642 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1643 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1644 default: binOp = node->getOp(); break;
1645 }
1646
1647 break;
1648 }
1649 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001650 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001651 binOp = glslang::EOpMul;
1652 break;
1653 case glslang::EOpOuterProduct:
1654 // two vectors multiplied to make a matrix
1655 binOp = glslang::EOpOuterProduct;
1656 break;
1657 case glslang::EOpDot:
1658 {
qining25262b32016-05-06 17:25:16 -04001659 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001660 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001661 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001662 binOp = glslang::EOpMul;
1663 break;
1664 }
1665 case glslang::EOpMod:
1666 // when an aggregate, this is the floating-point mod built-in function,
1667 // which can be emitted by the one in createBinaryOperation()
1668 binOp = glslang::EOpMod;
1669 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001670 case glslang::EOpEmitVertex:
1671 case glslang::EOpEndPrimitive:
1672 case glslang::EOpBarrier:
1673 case glslang::EOpMemoryBarrier:
1674 case glslang::EOpMemoryBarrierAtomicCounter:
1675 case glslang::EOpMemoryBarrierBuffer:
1676 case glslang::EOpMemoryBarrierImage:
1677 case glslang::EOpMemoryBarrierShared:
1678 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001679 case glslang::EOpAllMemoryBarrierWithGroupSync:
1680 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1681 case glslang::EOpWorkgroupMemoryBarrier:
1682 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001683 noReturnValue = true;
1684 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1685 break;
1686
John Kessenich426394d2015-07-23 10:22:48 -06001687 case glslang::EOpAtomicAdd:
1688 case glslang::EOpAtomicMin:
1689 case glslang::EOpAtomicMax:
1690 case glslang::EOpAtomicAnd:
1691 case glslang::EOpAtomicOr:
1692 case glslang::EOpAtomicXor:
1693 case glslang::EOpAtomicExchange:
1694 case glslang::EOpAtomicCompSwap:
1695 atomic = true;
1696 break;
1697
John Kessenich140f3df2015-06-26 16:58:36 -06001698 default:
1699 break;
1700 }
1701
1702 //
1703 // See if it maps to a regular operation.
1704 //
John Kessenich140f3df2015-06-26 16:58:36 -06001705 if (binOp != glslang::EOpNull) {
1706 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1707 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1708 assert(left && right);
1709
1710 builder.clearAccessChain();
1711 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001712 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001713
1714 builder.clearAccessChain();
1715 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001716 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001717
qining25262b32016-05-06 17:25:16 -04001718 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001719 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001720 left->getType().getBasicType(), reduceComparison);
1721
1722 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001723 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001724 builder.clearAccessChain();
1725 builder.setAccessChainRValue(result);
1726
1727 return false;
1728 }
1729
John Kessenich426394d2015-07-23 10:22:48 -06001730 //
1731 // Create the list of operands.
1732 //
John Kessenich140f3df2015-06-26 16:58:36 -06001733 glslang::TIntermSequence& glslangOperands = node->getSequence();
1734 std::vector<spv::Id> operands;
1735 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001736 // special case l-value operands; there are just a few
1737 bool lvalue = false;
1738 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001739 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001740 case glslang::EOpModf:
1741 if (arg == 1)
1742 lvalue = true;
1743 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001744 case glslang::EOpInterpolateAtSample:
1745 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001746#ifdef AMD_EXTENSIONS
1747 case glslang::EOpInterpolateAtVertex:
1748#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001749 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001750 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001751
1752 // Does it need a swizzle inversion? If so, evaluation is inverted;
1753 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001754 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001755 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1756 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1757 }
Rex Xu7a26c172015-12-08 17:12:09 +08001758 break;
Rex Xud4782c12015-09-06 16:30:11 +08001759 case glslang::EOpAtomicAdd:
1760 case glslang::EOpAtomicMin:
1761 case glslang::EOpAtomicMax:
1762 case glslang::EOpAtomicAnd:
1763 case glslang::EOpAtomicOr:
1764 case glslang::EOpAtomicXor:
1765 case glslang::EOpAtomicExchange:
1766 case glslang::EOpAtomicCompSwap:
1767 if (arg == 0)
1768 lvalue = true;
1769 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001770 case glslang::EOpAddCarry:
1771 case glslang::EOpSubBorrow:
1772 if (arg == 2)
1773 lvalue = true;
1774 break;
1775 case glslang::EOpUMulExtended:
1776 case glslang::EOpIMulExtended:
1777 if (arg >= 2)
1778 lvalue = true;
1779 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001780 default:
1781 break;
1782 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001783 builder.clearAccessChain();
1784 if (invertedType != spv::NoType && arg == 0)
1785 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1786 else
1787 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001788 if (lvalue)
1789 operands.push_back(builder.accessChainGetLValue());
1790 else
John Kessenich32cfd492016-02-02 12:37:46 -07001791 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001792 }
John Kessenich426394d2015-07-23 10:22:48 -06001793
1794 if (atomic) {
1795 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001796 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001797 } else {
1798 // Pass through to generic operations.
1799 switch (glslangOperands.size()) {
1800 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001801 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001802 break;
1803 case 1:
qining25262b32016-05-06 17:25:16 -04001804 result = createUnaryOperation(
1805 node->getOp(), precision,
1806 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001807 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001808 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001809 break;
1810 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001811 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001812 break;
1813 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001814 if (invertedType)
1815 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001816 }
1817
1818 if (noReturnValue)
1819 return false;
1820
1821 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001822 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001823 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001824 } else {
1825 builder.clearAccessChain();
1826 builder.setAccessChainRValue(result);
1827 return false;
1828 }
1829}
1830
John Kessenich433e9ff2017-01-26 20:31:11 -07001831// This path handles both if-then-else and ?:
1832// The if-then-else has a node type of void, while
1833// ?: has either a void or a non-void node type
1834//
1835// Leaving the result, when not void:
1836// GLSL only has r-values as the result of a :?, but
1837// if we have an l-value, that can be more efficient if it will
1838// become the base of a complex r-value expression, because the
1839// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001840bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1841{
John Kessenich433e9ff2017-01-26 20:31:11 -07001842 // See if it simple and safe to generate OpSelect instead of using control flow.
1843 // Crucially, side effects must be avoided, and there are performance trade-offs.
1844 // Return true if good idea (and safe) for OpSelect, false otherwise.
1845 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001846 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1847 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001848 return false;
1849
1850 if (node->getTrueBlock() == nullptr ||
1851 node->getFalseBlock() == nullptr)
1852 return false;
1853
1854 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1855 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1856
1857 // return true if a single operand to ? : is okay for OpSelect
1858 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001859 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001860 };
1861
1862 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1863 operandOkay(node->getFalseBlock()->getAsTyped());
1864 };
1865
1866 // Emit OpSelect for this selection.
1867 const auto handleAsOpSelect = [&]() {
1868 node->getCondition()->traverse(this);
1869 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1870 node->getTrueBlock()->traverse(this);
1871 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1872 node->getFalseBlock()->traverse(this);
1873 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1874
John Kesseniche434ad92017-03-30 10:09:28 -06001875 // smear condition to vector, if necessary (AST is always scalar)
1876 if (builder.isVector(trueValue))
1877 condition = builder.smearScalar(spv::NoPrecision, condition,
1878 builder.makeVectorType(builder.makeBoolType(),
1879 builder.getNumComponents(trueValue)));
1880
1881 spv::Id select = builder.createTriOp(spv::OpSelect,
1882 convertGlslangToSpvType(node->getType()), condition,
1883 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001884 builder.clearAccessChain();
1885 builder.setAccessChainRValue(select);
1886 };
1887
1888 // Try for OpSelect
1889
1890 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001891 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1892 if (node->getType().getQualifier().isSpecConstant())
1893 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1894
John Kessenich433e9ff2017-01-26 20:31:11 -07001895 handleAsOpSelect();
1896 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001897 }
1898
John Kessenich433e9ff2017-01-26 20:31:11 -07001899 // Instead, emit control flow...
1900
1901 // Don't handle results as temporaries, because there will be two names
1902 // and better to leave SSA to later passes.
1903 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1904 ? spv::NoResult
1905 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1906
John Kessenich140f3df2015-06-26 16:58:36 -06001907 // emit the condition before doing anything with selection
1908 node->getCondition()->traverse(this);
1909
1910 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001911 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001912
John Kessenich433e9ff2017-01-26 20:31:11 -07001913 // emit the "then" statement
1914 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001915 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001916 if (result != spv::NoResult)
1917 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001918 }
1919
John Kessenich433e9ff2017-01-26 20:31:11 -07001920 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001921 ifBuilder.makeBeginElse();
1922 // emit the "else" statement
1923 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001924 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001925 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001926 }
1927
John Kessenich433e9ff2017-01-26 20:31:11 -07001928 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001929 ifBuilder.makeEndIf();
1930
John Kessenich433e9ff2017-01-26 20:31:11 -07001931 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001932 // GLSL only has r-values as the result of a :?, but
1933 // if we have an l-value, that can be more efficient if it will
1934 // become the base of a complex r-value expression, because the
1935 // next layer copies r-values into memory to use the access-chain mechanism
1936 builder.clearAccessChain();
1937 builder.setAccessChainLValue(result);
1938 }
1939
1940 return false;
1941}
1942
1943bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1944{
1945 // emit and get the condition before doing anything with switch
1946 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001947 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001948
1949 // browse the children to sort out code segments
1950 int defaultSegment = -1;
1951 std::vector<TIntermNode*> codeSegments;
1952 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1953 std::vector<int> caseValues;
1954 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1955 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1956 TIntermNode* child = *c;
1957 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001958 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001959 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001960 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001961 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1962 } else
1963 codeSegments.push_back(child);
1964 }
1965
qining25262b32016-05-06 17:25:16 -04001966 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001967 // statements between the last case and the end of the switch statement
1968 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1969 (int)codeSegments.size() == defaultSegment)
1970 codeSegments.push_back(nullptr);
1971
1972 // make the switch statement
1973 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001974 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001975
1976 // emit all the code in the segments
1977 breakForLoop.push(false);
1978 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1979 builder.nextSwitchSegment(segmentBlocks, s);
1980 if (codeSegments[s])
1981 codeSegments[s]->traverse(this);
1982 else
1983 builder.addSwitchBreak();
1984 }
1985 breakForLoop.pop();
1986
1987 builder.endSwitch(segmentBlocks);
1988
1989 return false;
1990}
1991
1992void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1993{
1994 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001995 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001996
1997 builder.clearAccessChain();
1998 builder.setAccessChainRValue(constant);
1999}
2000
2001bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2002{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002003 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002004 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002005
2006 // Loop control:
2007 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2008
2009 // TODO: dependency length
2010
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002011 // Spec requires back edges to target header blocks, and every header block
2012 // must dominate its merge block. Make a header block first to ensure these
2013 // conditions are met. By definition, it will contain OpLoopMerge, followed
2014 // by a block-ending branch. But we don't want to put any other body/test
2015 // instructions in it, since the body/test may have arbitrary instructions,
2016 // including merges of its own.
2017 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002018 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002019 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002020 spv::Block& test = builder.makeNewBlock();
2021 builder.createBranch(&test);
2022
2023 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002024 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002025 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002026 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002027 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2028
2029 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002030 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002031 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002032 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002033 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002034 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002035
2036 builder.setBuildPoint(&blocks.continue_target);
2037 if (node->getTerminal())
2038 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002039 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002040 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002041 builder.createBranch(&blocks.body);
2042
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002043 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002044 builder.setBuildPoint(&blocks.body);
2045 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002046 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002047 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002048 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002049
2050 builder.setBuildPoint(&blocks.continue_target);
2051 if (node->getTerminal())
2052 node->getTerminal()->traverse(this);
2053 if (node->getTest()) {
2054 node->getTest()->traverse(this);
2055 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002056 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002057 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002058 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002059 // TODO: unless there was a break/return/discard instruction
2060 // somewhere in the body, this is an infinite loop, so we should
2061 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002062 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002063 }
John Kessenich140f3df2015-06-26 16:58:36 -06002064 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002065 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002066 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002067 return false;
2068}
2069
2070bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2071{
2072 if (node->getExpression())
2073 node->getExpression()->traverse(this);
2074
2075 switch (node->getFlowOp()) {
2076 case glslang::EOpKill:
2077 builder.makeDiscard();
2078 break;
2079 case glslang::EOpBreak:
2080 if (breakForLoop.top())
2081 builder.createLoopExit();
2082 else
2083 builder.addSwitchBreak();
2084 break;
2085 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002086 builder.createLoopContinue();
2087 break;
2088 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002089 if (node->getExpression()) {
2090 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2091 spv::Id returnId = accessChainLoad(glslangReturnType);
2092 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2093 builder.clearAccessChain();
2094 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2095 builder.setAccessChainLValue(copyId);
2096 multiTypeStore(glslangReturnType, returnId);
2097 returnId = builder.createLoad(copyId);
2098 }
2099 builder.makeReturn(false, returnId);
2100 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002101 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002102
2103 builder.clearAccessChain();
2104 break;
2105
2106 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002107 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002108 break;
2109 }
2110
2111 return false;
2112}
2113
2114spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2115{
qining25262b32016-05-06 17:25:16 -04002116 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002117 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002118 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002119 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002120 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002121 }
2122
2123 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002124 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002125 spv::Id spvType = convertGlslangToSpvType(node->getType());
2126
Rex Xuf89ad982017-04-07 23:22:33 +08002127#ifdef AMD_EXTENSIONS
2128 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16);
2129 if (contains16BitType) {
2130 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2131 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2132 builder.addCapability(spv::CapabilityStorageInputOutput16);
2133 } else if (storageClass == spv::StorageClassPushConstant) {
2134 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2135 builder.addCapability(spv::CapabilityStoragePushConstant16);
2136 } else if (storageClass == spv::StorageClassUniform) {
2137 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2138 builder.addCapability(spv::CapabilityStorageUniform16);
2139 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2140 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2141 }
2142 }
2143#endif
2144
John Kessenich140f3df2015-06-26 16:58:36 -06002145 const char* name = node->getName().c_str();
2146 if (glslang::IsAnonymous(name))
2147 name = "";
2148
2149 return builder.createVariable(storageClass, spvType, name);
2150}
2151
2152// Return type Id of the sampled type.
2153spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2154{
2155 switch (sampler.type) {
2156 case glslang::EbtFloat: return builder.makeFloatType(32);
2157 case glslang::EbtInt: return builder.makeIntType(32);
2158 case glslang::EbtUint: return builder.makeUintType(32);
2159 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002160 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002161 return builder.makeFloatType(32);
2162 }
2163}
2164
John Kessenich8c8505c2016-07-26 12:50:38 -06002165// If node is a swizzle operation, return the type that should be used if
2166// the swizzle base is first consumed by another operation, before the swizzle
2167// is applied.
2168spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2169{
John Kessenichecba76f2017-01-06 00:34:48 -07002170 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002171 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2172 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2173 else
2174 return spv::NoType;
2175}
2176
2177// When inverting a swizzle with a parent op, this function
2178// will apply the swizzle operation to a completed parent operation.
2179spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2180{
2181 std::vector<unsigned> swizzle;
2182 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2183 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2184}
2185
John Kessenich8c8505c2016-07-26 12:50:38 -06002186// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2187void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2188{
2189 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2190 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2191 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2192}
2193
John Kessenich3ac051e2015-12-20 11:29:16 -07002194// Convert from a glslang type to an SPV type, by calling into a
2195// recursive version of this function. This establishes the inherited
2196// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002197spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2198{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002199 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002200}
2201
2202// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002203// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002204// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002205spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002206{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002207 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002208
2209 switch (type.getBasicType()) {
2210 case glslang::EbtVoid:
2211 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002212 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002213 break;
2214 case glslang::EbtFloat:
2215 spvType = builder.makeFloatType(32);
2216 break;
2217 case glslang::EbtDouble:
2218 spvType = builder.makeFloatType(64);
2219 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002220#ifdef AMD_EXTENSIONS
2221 case glslang::EbtFloat16:
2222 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002223 spvType = builder.makeFloatType(16);
2224 break;
2225#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002226 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002227 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2228 // a 32-bit int where non-0 means true.
2229 if (explicitLayout != glslang::ElpNone)
2230 spvType = builder.makeUintType(32);
2231 else
2232 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002233 break;
2234 case glslang::EbtInt:
2235 spvType = builder.makeIntType(32);
2236 break;
2237 case glslang::EbtUint:
2238 spvType = builder.makeUintType(32);
2239 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002240 case glslang::EbtInt64:
2241 builder.addCapability(spv::CapabilityInt64);
2242 spvType = builder.makeIntType(64);
2243 break;
2244 case glslang::EbtUint64:
2245 builder.addCapability(spv::CapabilityInt64);
2246 spvType = builder.makeUintType(64);
2247 break;
John Kessenich426394d2015-07-23 10:22:48 -06002248 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002249 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002250 spvType = builder.makeUintType(32);
2251 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002252 case glslang::EbtSampler:
2253 {
2254 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002255 if (sampler.sampler) {
2256 // pure sampler
2257 spvType = builder.makeSamplerType();
2258 } else {
2259 // an image is present, make its type
2260 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2261 sampler.image ? 2 : 1, TranslateImageFormat(type));
2262 if (sampler.combined) {
2263 // already has both image and sampler, make the combined type
2264 spvType = builder.makeSampledImageType(spvType);
2265 }
John Kessenich55e7d112015-11-15 21:33:39 -07002266 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002267 }
John Kessenich140f3df2015-06-26 16:58:36 -06002268 break;
2269 case glslang::EbtStruct:
2270 case glslang::EbtBlock:
2271 {
2272 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002273 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002274
2275 // Try to share structs for different layouts, but not yet for other
2276 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002277 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002278 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002279 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002280 break;
2281
2282 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002283 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002284 memberRemapper[glslangMembers].resize(glslangMembers->size());
2285 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002286 }
2287 break;
2288 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002289 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002290 break;
2291 }
2292
2293 if (type.isMatrix())
2294 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2295 else {
2296 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2297 if (type.getVectorSize() > 1)
2298 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2299 }
2300
2301 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002302 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2303
John Kessenichc9a80832015-09-12 12:17:44 -06002304 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002305 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002306 // We need to decorate array strides for types needing explicit layout, except blocks.
2307 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002308 // Use a dummy glslang type for querying internal strides of
2309 // arrays of arrays, but using just a one-dimensional array.
2310 glslang::TType simpleArrayType(type, 0); // deference type of the array
2311 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2312 simpleArrayType.getArraySizes().dereference();
2313
2314 // Will compute the higher-order strides here, rather than making a whole
2315 // pile of types and doing repetitive recursion on their contents.
2316 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2317 }
John Kessenichf8842e52016-01-04 19:22:56 -07002318
2319 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002320 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002321 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002322 if (stride > 0)
2323 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002324 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002325 }
2326 } else {
2327 // single-dimensional array, and don't yet have stride
2328
John Kessenichf8842e52016-01-04 19:22:56 -07002329 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002330 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2331 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002332 }
John Kessenich31ed4832015-09-09 17:51:38 -06002333
John Kessenichc9a80832015-09-12 12:17:44 -06002334 // Do the outer dimension, which might not be known for a runtime-sized array
2335 if (type.isRuntimeSizedArray()) {
2336 spvType = builder.makeRuntimeArray(spvType);
2337 } else {
2338 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002339 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002340 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002341 if (stride > 0)
2342 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002343 }
2344
2345 return spvType;
2346}
2347
John Kessenich0e737842017-03-24 18:38:16 -06002348// TODO: this functionality should exist at a higher level, in creating the AST
2349//
2350// Identify interface members that don't have their required extension turned on.
2351//
2352bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2353{
2354 auto& extensions = glslangIntermediate->getRequestedExtensions();
2355
Rex Xubcf291a2017-03-29 23:01:36 +08002356 if (member.getFieldName() == "gl_ViewportMask" &&
2357 extensions.find("GL_NV_viewport_array2") == extensions.end())
2358 return true;
2359 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2360 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2361 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002362 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2363 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2364 return true;
2365 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2366 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2367 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002368 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2369 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2370 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002371
2372 return false;
2373};
2374
John Kessenich6090df02016-06-30 21:18:02 -06002375// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2376// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2377// Mutually recursive with convertGlslangToSpvType().
2378spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2379 const glslang::TTypeList* glslangMembers,
2380 glslang::TLayoutPacking explicitLayout,
2381 const glslang::TQualifier& qualifier)
2382{
2383 // Create a vector of struct types for SPIR-V to consume
2384 std::vector<spv::Id> spvMembers;
2385 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2386 int locationOffset = 0; // for use across struct members, when they are called recursively
2387 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2388 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2389 if (glslangMember.hiddenMember()) {
2390 ++memberDelta;
2391 if (type.getBasicType() == glslang::EbtBlock)
2392 memberRemapper[glslangMembers][i] = -1;
2393 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002394 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002395 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002396 if (filterMember(glslangMember))
2397 continue;
2398 }
John Kessenich6090df02016-06-30 21:18:02 -06002399 // modify just this child's view of the qualifier
2400 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2401 InheritQualifiers(memberQualifier, qualifier);
2402
2403 // manually inherit location; it's more complex
2404 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2405 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2406 if (qualifier.hasLocation())
2407 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2408
2409 // recurse
2410 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2411 }
2412 }
2413
2414 // Make the SPIR-V type
2415 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002416 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002417 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2418
2419 // Decorate it
2420 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2421
2422 return spvType;
2423}
2424
2425void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2426 const glslang::TTypeList* glslangMembers,
2427 glslang::TLayoutPacking explicitLayout,
2428 const glslang::TQualifier& qualifier,
2429 spv::Id spvType)
2430{
2431 // Name and decorate the non-hidden members
2432 int offset = -1;
2433 int locationOffset = 0; // for use within the members of this struct
2434 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2435 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2436 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002437 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002438 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002439 if (filterMember(glslangMember))
2440 continue;
2441 }
John Kessenich6090df02016-06-30 21:18:02 -06002442
2443 // modify just this child's view of the qualifier
2444 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2445 InheritQualifiers(memberQualifier, qualifier);
2446
2447 // using -1 above to indicate a hidden member
2448 if (member >= 0) {
2449 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2450 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2451 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2452 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002453 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2454 type.getQualifier().storage == glslang::EvqVaryingOut) {
2455 if (type.getBasicType() == glslang::EbtBlock ||
2456 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002457 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2458 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2459 }
2460 }
2461 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2462
2463 if (qualifier.storage == glslang::EvqBuffer) {
2464 std::vector<spv::Decoration> memory;
2465 TranslateMemoryDecoration(memberQualifier, memory);
2466 for (unsigned int i = 0; i < memory.size(); ++i)
2467 addMemberDecoration(spvType, member, memory[i]);
2468 }
2469
John Kessenich2f47bc92016-06-30 21:47:35 -06002470 // Compute location decoration; tricky based on whether inheritance is at play and
2471 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002472 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2473 // probably move to the linker stage of the front end proper, and just have the
2474 // answer sitting already distributed throughout the individual member locations.
2475 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002476 // Ignore member locations if the container is an array, as that's
2477 // ill-specified and decisions have been made to not allow this anyway.
2478 // The object itself must have a location, and that comes out from decorating the object,
2479 // not the type (this code decorates types).
2480 if (! type.isArray()) {
2481 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2482 // struct members should not have explicit locations
2483 assert(type.getBasicType() != glslang::EbtStruct);
2484 location = memberQualifier.layoutLocation;
2485 } else if (type.getBasicType() != glslang::EbtBlock) {
2486 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2487 // The members, and their nested types, must not themselves have Location decorations.
2488 } else if (qualifier.hasLocation()) // inheritance
2489 location = qualifier.layoutLocation + locationOffset;
2490 }
John Kessenich6090df02016-06-30 21:18:02 -06002491 if (location >= 0)
2492 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2493
John Kessenich2f47bc92016-06-30 21:47:35 -06002494 if (qualifier.hasLocation()) // track for upcoming inheritance
2495 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2496
John Kessenich6090df02016-06-30 21:18:02 -06002497 // component, XFB, others
2498 if (glslangMember.getQualifier().hasComponent())
2499 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2500 if (glslangMember.getQualifier().hasXfbOffset())
2501 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2502 else if (explicitLayout != glslang::ElpNone) {
2503 // figure out what to do with offset, which is accumulating
2504 int nextOffset;
2505 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2506 if (offset >= 0)
2507 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2508 offset = nextOffset;
2509 }
2510
2511 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2512 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2513
2514 // built-in variable decorations
2515 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002516 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002517 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002518
2519#ifdef NV_EXTENSIONS
2520 if (builtIn == spv::BuiltInLayer) {
2521 // SPV_NV_viewport_array2 extension
2522 if (glslangMember.getQualifier().layoutViewportRelative){
2523 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2524 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2525 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2526 }
2527 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2528 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2529 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2530 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2531 }
2532 }
chaocdf3956c2017-02-14 14:52:34 -08002533 if (glslangMember.getQualifier().layoutPassthrough) {
2534 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2535 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2536 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2537 }
chaoc771d89f2017-01-13 01:10:53 -08002538#endif
John Kessenich6090df02016-06-30 21:18:02 -06002539 }
2540 }
2541
2542 // Decorate the structure
2543 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002544 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002545 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2546 builder.addCapability(spv::CapabilityGeometryStreams);
2547 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2548 }
2549 if (glslangIntermediate->getXfbMode()) {
2550 builder.addCapability(spv::CapabilityTransformFeedback);
2551 if (type.getQualifier().hasXfbStride())
2552 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2553 if (type.getQualifier().hasXfbBuffer())
2554 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2555 }
2556}
2557
John Kessenich6c292d32016-02-15 20:58:50 -07002558// Turn the expression forming the array size into an id.
2559// This is not quite trivial, because of specialization constants.
2560// Sometimes, a raw constant is turned into an Id, and sometimes
2561// a specialization constant expression is.
2562spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2563{
2564 // First, see if this is sized with a node, meaning a specialization constant:
2565 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2566 if (specNode != nullptr) {
2567 builder.clearAccessChain();
2568 specNode->traverse(this);
2569 return accessChainLoad(specNode->getAsTyped()->getType());
2570 }
qining25262b32016-05-06 17:25:16 -04002571
John Kessenich6c292d32016-02-15 20:58:50 -07002572 // Otherwise, need a compile-time (front end) size, get it:
2573 int size = arraySizes.getDimSize(dim);
2574 assert(size > 0);
2575 return builder.makeUintConstant(size);
2576}
2577
John Kessenich103bef92016-02-08 21:38:15 -07002578// Wrap the builder's accessChainLoad to:
2579// - localize handling of RelaxedPrecision
2580// - use the SPIR-V inferred type instead of another conversion of the glslang type
2581// (avoids unnecessary work and possible type punning for structures)
2582// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002583spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2584{
John Kessenich103bef92016-02-08 21:38:15 -07002585 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2586 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2587
2588 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002589 if (type.getBasicType() == glslang::EbtBool) {
2590 if (builder.isScalarType(nominalTypeId)) {
2591 // Conversion for bool
2592 spv::Id boolType = builder.makeBoolType();
2593 if (nominalTypeId != boolType)
2594 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2595 } else if (builder.isVectorType(nominalTypeId)) {
2596 // Conversion for bvec
2597 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2598 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2599 if (nominalTypeId != bvecType)
2600 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2601 }
2602 }
John Kessenich103bef92016-02-08 21:38:15 -07002603
2604 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002605}
2606
Rex Xu27253232016-02-23 17:51:09 +08002607// Wrap the builder's accessChainStore to:
2608// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002609//
2610// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002611void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2612{
2613 // Need to convert to abstract types when necessary
2614 if (type.getBasicType() == glslang::EbtBool) {
2615 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2616
2617 if (builder.isScalarType(nominalTypeId)) {
2618 // Conversion for bool
2619 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002620 if (nominalTypeId != boolType) {
2621 // keep these outside arguments, for determinant order-of-evaluation
2622 spv::Id one = builder.makeUintConstant(1);
2623 spv::Id zero = builder.makeUintConstant(0);
2624 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2625 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002626 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002627 } else if (builder.isVectorType(nominalTypeId)) {
2628 // Conversion for bvec
2629 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2630 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002631 if (nominalTypeId != bvecType) {
2632 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002633 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2634 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2635 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002636 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002637 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2638 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002639 }
2640 }
2641
2642 builder.accessChainStore(rvalue);
2643}
2644
John Kessenich4bf71552016-09-02 11:20:21 -06002645// For storing when types match at the glslang level, but not might match at the
2646// SPIR-V level.
2647//
2648// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002649// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002650// as in a member-decorated way.
2651//
2652// NOTE: This function can handle any store request; if it's not special it
2653// simplifies to a simple OpStore.
2654//
2655// Implicitly uses the existing builder.accessChain as the storage target.
2656void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2657{
John Kessenichb3e24e42016-09-11 12:33:43 -06002658 // we only do the complex path here if it's an aggregate
2659 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002660 accessChainStore(type, rValue);
2661 return;
2662 }
2663
John Kessenichb3e24e42016-09-11 12:33:43 -06002664 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002665 spv::Id rType = builder.getTypeId(rValue);
2666 spv::Id lValue = builder.accessChainGetLValue();
2667 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2668 if (lType == rType) {
2669 accessChainStore(type, rValue);
2670 return;
2671 }
2672
John Kessenichb3e24e42016-09-11 12:33:43 -06002673 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002674 // where the two types were the same type in GLSL. This requires member
2675 // by member copy, recursively.
2676
John Kessenichb3e24e42016-09-11 12:33:43 -06002677 // If an array, copy element by element.
2678 if (type.isArray()) {
2679 glslang::TType glslangElementType(type, 0);
2680 spv::Id elementRType = builder.getContainedTypeId(rType);
2681 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2682 // get the source member
2683 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002684
John Kessenichb3e24e42016-09-11 12:33:43 -06002685 // set up the target storage
2686 builder.clearAccessChain();
2687 builder.setAccessChainLValue(lValue);
2688 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002689
John Kessenichb3e24e42016-09-11 12:33:43 -06002690 // store the member
2691 multiTypeStore(glslangElementType, elementRValue);
2692 }
2693 } else {
2694 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002695
John Kessenichb3e24e42016-09-11 12:33:43 -06002696 // loop over structure members
2697 const glslang::TTypeList& members = *type.getStruct();
2698 for (int m = 0; m < (int)members.size(); ++m) {
2699 const glslang::TType& glslangMemberType = *members[m].type;
2700
2701 // get the source member
2702 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2703 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2704
2705 // set up the target storage
2706 builder.clearAccessChain();
2707 builder.setAccessChainLValue(lValue);
2708 builder.accessChainPush(builder.makeIntConstant(m));
2709
2710 // store the member
2711 multiTypeStore(glslangMemberType, memberRValue);
2712 }
John Kessenich4bf71552016-09-02 11:20:21 -06002713 }
2714}
2715
John Kessenichf85e8062015-12-19 13:57:10 -07002716// Decide whether or not this type should be
2717// decorated with offsets and strides, and if so
2718// whether std140 or std430 rules should be applied.
2719glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002720{
John Kessenichf85e8062015-12-19 13:57:10 -07002721 // has to be a block
2722 if (type.getBasicType() != glslang::EbtBlock)
2723 return glslang::ElpNone;
2724
2725 // has to be a uniform or buffer block
2726 if (type.getQualifier().storage != glslang::EvqUniform &&
2727 type.getQualifier().storage != glslang::EvqBuffer)
2728 return glslang::ElpNone;
2729
2730 // return the layout to use
2731 switch (type.getQualifier().layoutPacking) {
2732 case glslang::ElpStd140:
2733 case glslang::ElpStd430:
2734 return type.getQualifier().layoutPacking;
2735 default:
2736 return glslang::ElpNone;
2737 }
John Kessenich31ed4832015-09-09 17:51:38 -06002738}
2739
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002740// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002741int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002742{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002743 int size;
John Kessenich49987892015-12-29 17:11:44 -07002744 int stride;
2745 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002746
2747 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002748}
2749
John Kessenich49987892015-12-29 17:11:44 -07002750// 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 -07002751// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002752int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002753{
John Kessenich49987892015-12-29 17:11:44 -07002754 glslang::TType elementType;
2755 elementType.shallowCopy(matrixType);
2756 elementType.clearArraySizes();
2757
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002758 int size;
John Kessenich49987892015-12-29 17:11:44 -07002759 int stride;
2760 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2761
2762 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002763}
2764
John Kessenich5e4b1242015-08-06 22:53:06 -06002765// Given a member type of a struct, realign the current offset for it, and compute
2766// the next (not yet aligned) offset for the next member, which will get aligned
2767// on the next call.
2768// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2769// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2770// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002771void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002772 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002773{
2774 // this will get a positive value when deemed necessary
2775 nextOffset = -1;
2776
John Kessenich5e4b1242015-08-06 22:53:06 -06002777 // override anything in currentOffset with user-set offset
2778 if (memberType.getQualifier().hasOffset())
2779 currentOffset = memberType.getQualifier().layoutOffset;
2780
2781 // It could be that current linker usage in glslang updated all the layoutOffset,
2782 // in which case the following code does not matter. But, that's not quite right
2783 // once cross-compilation unit GLSL validation is done, as the original user
2784 // settings are needed in layoutOffset, and then the following will come into play.
2785
John Kessenichf85e8062015-12-19 13:57:10 -07002786 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002787 if (! memberType.getQualifier().hasOffset())
2788 currentOffset = -1;
2789
2790 return;
2791 }
2792
John Kessenichf85e8062015-12-19 13:57:10 -07002793 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002794 if (currentOffset < 0)
2795 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002796
John Kessenich5e4b1242015-08-06 22:53:06 -06002797 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2798 // but possibly not yet correctly aligned.
2799
2800 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002801 int dummyStride;
2802 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002803
2804 // Adjust alignment for HLSL rules
2805 if (glslangIntermediate->usingHlslOFfsets() &&
2806 ! memberType.isArray() && memberType.isVector()) {
2807 int dummySize;
2808 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2809 if (componentAlignment <= 4)
2810 memberAlignment = componentAlignment;
2811 }
2812
2813 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002814 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002815
2816 // Bump up to vec4 if there is a bad straddle
2817 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2818 glslang::RoundToPow2(currentOffset, 16);
2819
John Kessenich5e4b1242015-08-06 22:53:06 -06002820 nextOffset = currentOffset + memberSize;
2821}
2822
David Netoa901ffe2016-06-08 14:11:40 +01002823void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002824{
David Netoa901ffe2016-06-08 14:11:40 +01002825 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2826 switch (glslangBuiltIn)
2827 {
2828 case glslang::EbvClipDistance:
2829 case glslang::EbvCullDistance:
2830 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002831#ifdef NV_EXTENSIONS
2832 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002833 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002834 case glslang::EbvViewportMaskNV:
2835 case glslang::EbvSecondaryPositionNV:
2836 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002837 case glslang::EbvPositionPerViewNV:
2838 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002839#endif
David Netoa901ffe2016-06-08 14:11:40 +01002840 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2841 // Alternately, we could just call this for any glslang built-in, since the
2842 // capability already guards against duplicates.
2843 TranslateBuiltInDecoration(glslangBuiltIn, false);
2844 break;
2845 default:
2846 // Capabilities were already generated when the struct was declared.
2847 break;
2848 }
John Kessenichebb50532016-05-16 19:22:05 -06002849}
2850
John Kessenich6fccb3c2016-09-19 16:01:41 -06002851bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002852{
John Kessenicheee9d532016-09-19 18:09:30 -06002853 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002854}
2855
2856// Make all the functions, skeletally, without actually visiting their bodies.
2857void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2858{
2859 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2860 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002861 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002862 continue;
2863
2864 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002865 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002866 //
qining25262b32016-05-06 17:25:16 -04002867 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002868 // function. What it is an address of varies:
2869 //
John Kessenich4bf71552016-09-02 11:20:21 -06002870 // - "in" parameters not marked as "const" can be written to without modifying the calling
2871 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002872 //
2873 // - "const in" parameters can just be the r-value, as no writes need occur.
2874 //
John Kessenich4bf71552016-09-02 11:20:21 -06002875 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2876 // GLSL has copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
John Kessenich140f3df2015-06-26 16:58:36 -06002877
2878 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002879 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002880 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2881
John Kessenich37789792017-03-21 23:56:40 -06002882 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName;
2883
John Kessenich140f3df2015-06-26 16:58:36 -06002884 for (int p = 0; p < (int)parameters.size(); ++p) {
2885 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2886 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002887 // can we pass by reference?
2888 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002889 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002890 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002891 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06002892 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002893 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002894 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2895 else
John Kessenich4bf71552016-09-02 11:20:21 -06002896 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002897 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002898 paramTypes.push_back(typeId);
2899 }
2900
2901 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002902 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2903 convertGlslangToSpvType(glslFunction->getType()),
2904 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002905 if (implicitThis)
2906 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002907
2908 // Track function to emit/call later
2909 functionMap[glslFunction->getName().c_str()] = function;
2910
2911 // Set the parameter id's
2912 for (int p = 0; p < (int)parameters.size(); ++p) {
2913 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2914 // give a name too
2915 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2916 }
2917 }
2918}
2919
2920// Process all the initializers, while skipping the functions and link objects
2921void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2922{
2923 builder.setBuildPoint(shaderEntry->getLastBlock());
2924 for (int i = 0; i < (int)initializers.size(); ++i) {
2925 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2926 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2927
2928 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002929 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002930 initializer->traverse(this);
2931 }
2932 }
2933}
2934
2935// Process all the functions, while skipping initializers.
2936void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2937{
2938 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2939 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002940 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002941 node->traverse(this);
2942 }
2943}
2944
2945void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2946{
qining25262b32016-05-06 17:25:16 -04002947 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002948 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002949 currentFunction = functionMap[node->getName().c_str()];
2950 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002951 builder.setBuildPoint(functionBlock);
2952}
2953
Rex Xu04db3f52015-09-16 11:44:02 +08002954void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002955{
Rex Xufc618912015-09-09 16:42:49 +08002956 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002957
2958 glslang::TSampler sampler = {};
2959 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002960 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002961 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2962 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2963 }
2964
John Kessenich140f3df2015-06-26 16:58:36 -06002965 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2966 builder.clearAccessChain();
2967 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002968
2969 // Special case l-value operands
2970 bool lvalue = false;
2971 switch (node.getOp()) {
2972 case glslang::EOpImageAtomicAdd:
2973 case glslang::EOpImageAtomicMin:
2974 case glslang::EOpImageAtomicMax:
2975 case glslang::EOpImageAtomicAnd:
2976 case glslang::EOpImageAtomicOr:
2977 case glslang::EOpImageAtomicXor:
2978 case glslang::EOpImageAtomicExchange:
2979 case glslang::EOpImageAtomicCompSwap:
2980 if (i == 0)
2981 lvalue = true;
2982 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002983 case glslang::EOpSparseImageLoad:
2984 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2985 lvalue = true;
2986 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002987 case glslang::EOpSparseTexture:
2988 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2989 lvalue = true;
2990 break;
2991 case glslang::EOpSparseTextureClamp:
2992 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2993 lvalue = true;
2994 break;
2995 case glslang::EOpSparseTextureLod:
2996 case glslang::EOpSparseTextureOffset:
2997 if (i == 3)
2998 lvalue = true;
2999 break;
3000 case glslang::EOpSparseTextureFetch:
3001 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3002 lvalue = true;
3003 break;
3004 case glslang::EOpSparseTextureFetchOffset:
3005 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3006 lvalue = true;
3007 break;
3008 case glslang::EOpSparseTextureLodOffset:
3009 case glslang::EOpSparseTextureGrad:
3010 case glslang::EOpSparseTextureOffsetClamp:
3011 if (i == 4)
3012 lvalue = true;
3013 break;
3014 case glslang::EOpSparseTextureGradOffset:
3015 case glslang::EOpSparseTextureGradClamp:
3016 if (i == 5)
3017 lvalue = true;
3018 break;
3019 case glslang::EOpSparseTextureGradOffsetClamp:
3020 if (i == 6)
3021 lvalue = true;
3022 break;
3023 case glslang::EOpSparseTextureGather:
3024 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3025 lvalue = true;
3026 break;
3027 case glslang::EOpSparseTextureGatherOffset:
3028 case glslang::EOpSparseTextureGatherOffsets:
3029 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3030 lvalue = true;
3031 break;
Rex Xufc618912015-09-09 16:42:49 +08003032 default:
3033 break;
3034 }
3035
Rex Xu6b86d492015-09-16 17:48:22 +08003036 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003037 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003038 else
John Kessenich32cfd492016-02-02 12:37:46 -07003039 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003040 }
3041}
3042
John Kessenichfc51d282015-08-19 13:34:18 -06003043void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003044{
John Kessenichfc51d282015-08-19 13:34:18 -06003045 builder.clearAccessChain();
3046 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003047 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003048}
John Kessenich140f3df2015-06-26 16:58:36 -06003049
John Kessenichfc51d282015-08-19 13:34:18 -06003050spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3051{
Rex Xufc618912015-09-09 16:42:49 +08003052 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06003053 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003054 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003055 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003056
John Kessenichfc51d282015-08-19 13:34:18 -06003057 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003058 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3059 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3060 std::vector<spv::Id> arguments;
3061 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003062 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003063 else
3064 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003065 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003066
3067 spv::Builder::TextureParameters params = { };
3068 params.sampler = arguments[0];
3069
Rex Xu04db3f52015-09-16 11:44:02 +08003070 glslang::TCrackedTextureOp cracked;
3071 node->crackTexture(sampler, cracked);
3072
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003073 const bool isUnsignedResult =
3074 node->getType().getBasicType() == glslang::EbtUint64 ||
3075 node->getType().getBasicType() == glslang::EbtUint;
3076
John Kessenichfc51d282015-08-19 13:34:18 -06003077 // Check for queries
3078 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003079 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3080 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003081 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003082
John Kessenichfc51d282015-08-19 13:34:18 -06003083 switch (node->getOp()) {
3084 case glslang::EOpImageQuerySize:
3085 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003086 if (arguments.size() > 1) {
3087 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003088 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003089 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003090 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003091 case glslang::EOpImageQuerySamples:
3092 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003093 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003094 case glslang::EOpTextureQueryLod:
3095 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003096 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003097 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003098 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003099 case glslang::EOpSparseTexelsResident:
3100 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003101 default:
3102 assert(0);
3103 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003104 }
John Kessenich140f3df2015-06-26 16:58:36 -06003105 }
3106
Rex Xufc618912015-09-09 16:42:49 +08003107 // Check for image functions other than queries
3108 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003109 std::vector<spv::Id> operands;
3110 auto opIt = arguments.begin();
3111 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003112
3113 // Handle subpass operations
3114 // TODO: GLSL should change to have the "MS" only on the type rather than the
3115 // built-in function.
3116 if (cracked.subpass) {
3117 // add on the (0,0) coordinate
3118 spv::Id zero = builder.makeIntConstant(0);
3119 std::vector<spv::Id> comps;
3120 comps.push_back(zero);
3121 comps.push_back(zero);
3122 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3123 if (sampler.ms) {
3124 operands.push_back(spv::ImageOperandsSampleMask);
3125 operands.push_back(*(opIt++));
3126 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003127 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003128 }
3129
John Kessenich56bab042015-09-16 10:54:31 -06003130 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003131 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003132 if (sampler.ms) {
3133 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003134 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003135 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003136 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3137 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003138 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003139 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003140 if (sampler.ms) {
3141 operands.push_back(*(opIt + 1));
3142 operands.push_back(spv::ImageOperandsSampleMask);
3143 operands.push_back(*opIt);
3144 } else
3145 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003146 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003147 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3148 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003149 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003150 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3151 builder.addCapability(spv::CapabilitySparseResidency);
3152 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3153 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3154
3155 if (sampler.ms) {
3156 operands.push_back(spv::ImageOperandsSampleMask);
3157 operands.push_back(*opIt++);
3158 }
3159
3160 // Create the return type that was a special structure
3161 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003162 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003163 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3164 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3165
3166 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3167
3168 // Decode the return type
3169 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3170 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003171 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003172 // Process image atomic operations
3173
3174 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3175 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003176 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003177
John Kessenich8c8505c2016-07-26 12:50:38 -06003178 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003179 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003180
3181 std::vector<spv::Id> operands;
3182 operands.push_back(pointer);
3183 for (; opIt != arguments.end(); ++opIt)
3184 operands.push_back(*opIt);
3185
John Kessenich8c8505c2016-07-26 12:50:38 -06003186 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003187 }
3188 }
3189
3190 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003191 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003192 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3193
John Kessenichfc51d282015-08-19 13:34:18 -06003194 // check for bias argument
3195 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003196 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003197 int nonBiasArgCount = 2;
3198 if (cracked.offset)
3199 ++nonBiasArgCount;
3200 if (cracked.grad)
3201 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003202 if (cracked.lodClamp)
3203 ++nonBiasArgCount;
3204 if (sparse)
3205 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003206
3207 if ((int)arguments.size() > nonBiasArgCount)
3208 bias = true;
3209 }
3210
John Kessenicha5c33d62016-06-02 23:45:21 -06003211 // See if the sampler param should really be just the SPV image part
3212 if (cracked.fetch) {
3213 // a fetch needs to have the image extracted first
3214 if (builder.isSampledImage(params.sampler))
3215 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3216 }
3217
John Kessenichfc51d282015-08-19 13:34:18 -06003218 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003219
John Kessenichfc51d282015-08-19 13:34:18 -06003220 params.coords = arguments[1];
3221 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003222 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003223
3224 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003225 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003226 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003227 ++extraArgs;
3228 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003229 params.Dref = arguments[2];
3230 ++extraArgs;
3231 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003232 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003233 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003234 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003235 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003236 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003237 dRefComp = builder.getNumComponents(params.coords) - 1;
3238 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003239 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3240 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003241
3242 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003243 if (cracked.lod) {
3244 params.lod = arguments[2];
3245 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003246 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3247 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3248 noImplicitLod = true;
3249 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003250
3251 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003252 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003253 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003254 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003255 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003256
3257 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003258 if (cracked.grad) {
3259 params.gradX = arguments[2 + extraArgs];
3260 params.gradY = arguments[3 + extraArgs];
3261 extraArgs += 2;
3262 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003263
3264 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003265 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003266 params.offset = arguments[2 + extraArgs];
3267 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003268 } else if (cracked.offsets) {
3269 params.offsets = arguments[2 + extraArgs];
3270 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003271 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003272
3273 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003274 if (cracked.lodClamp) {
3275 params.lodClamp = arguments[2 + extraArgs];
3276 ++extraArgs;
3277 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003278
3279 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003280 if (sparse) {
3281 params.texelOut = arguments[2 + extraArgs];
3282 ++extraArgs;
3283 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003284
3285 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003286 if (bias) {
3287 params.bias = arguments[2 + extraArgs];
3288 ++extraArgs;
3289 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003290
3291 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003292 if (cracked.gather && ! sampler.shadow) {
3293 // default component is 0, if missing, otherwise an argument
3294 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003295 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003296 ++extraArgs;
3297 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003298 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003299 }
3300 }
John Kessenichfc51d282015-08-19 13:34:18 -06003301
John Kessenich65336482016-06-16 14:06:26 -06003302 // projective component (might not to move)
3303 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3304 // are divided by the last component of P."
3305 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3306 // unused components will appear after all used components."
3307 if (cracked.proj) {
3308 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3309 int projTargetComp;
3310 switch (sampler.dim) {
3311 case glslang::Esd1D: projTargetComp = 1; break;
3312 case glslang::Esd2D: projTargetComp = 2; break;
3313 case glslang::EsdRect: projTargetComp = 2; break;
3314 default: projTargetComp = projSourceComp; break;
3315 }
3316 // copy the projective coordinate if we have to
3317 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003318 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003319 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3320 projSourceComp);
3321 params.coords = builder.createCompositeInsert(projComp, params.coords,
3322 builder.getTypeId(params.coords), projTargetComp);
3323 }
3324 }
3325
John Kessenich8c8505c2016-07-26 12:50:38 -06003326 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003327}
3328
3329spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3330{
3331 // Grab the function's pointer from the previously created function
3332 spv::Function* function = functionMap[node->getName().c_str()];
3333 if (! function)
3334 return 0;
3335
3336 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3337 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3338
3339 // See comments in makeFunctions() for details about the semantics for parameter passing.
3340 //
3341 // These imply we need a four step process:
3342 // 1. Evaluate the arguments
3343 // 2. Allocate and make copies of in, out, and inout arguments
3344 // 3. Make the call
3345 // 4. Copy back the results
3346
3347 // 1. Evaluate the arguments
3348 std::vector<spv::Builder::AccessChain> lValues;
3349 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003350 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003351 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003352 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003353 // build l-value
3354 builder.clearAccessChain();
3355 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003356 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003357 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003358 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003359 // save l-value
3360 lValues.push_back(builder.getAccessChain());
3361 } else {
3362 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003363 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003364 }
3365 }
3366
3367 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3368 // copy the original into that space.
3369 //
3370 // Also, build up the list of actual arguments to pass in for the call
3371 int lValueCount = 0;
3372 int rValueCount = 0;
3373 std::vector<spv::Id> spvArgs;
3374 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003375 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003376 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003377 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003378 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3379 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003380 builder.setAccessChain(lValues[lValueCount]);
3381 arg = builder.accessChainGetLValue();
3382 ++lValueCount;
3383 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003384 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003385 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3386 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3387 // need to copy the input into output space
3388 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003389 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003390 builder.clearAccessChain();
3391 builder.setAccessChainLValue(arg);
3392 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003393 }
3394 ++lValueCount;
3395 } else {
3396 arg = rValues[rValueCount];
3397 ++rValueCount;
3398 }
3399 spvArgs.push_back(arg);
3400 }
3401
3402 // 3. Make the call.
3403 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003404 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003405
3406 // 4. Copy back out an "out" arguments.
3407 lValueCount = 0;
3408 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003409 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003410 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3411 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3412 spv::Id copy = builder.createLoad(spvArgs[a]);
3413 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003414 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003415 }
3416 ++lValueCount;
3417 }
3418 }
3419
3420 return result;
3421}
3422
3423// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003424spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3425 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003426 spv::Id typeId, spv::Id left, spv::Id right,
3427 glslang::TBasicType typeProxy, bool reduceComparison)
3428{
Rex Xu8ff43de2016-04-22 16:51:45 +08003429 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003430#ifdef AMD_EXTENSIONS
3431 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3432#else
John Kessenich140f3df2015-06-26 16:58:36 -06003433 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003434#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003435 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003436
3437 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003438 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003439 bool comparison = false;
3440
3441 switch (op) {
3442 case glslang::EOpAdd:
3443 case glslang::EOpAddAssign:
3444 if (isFloat)
3445 binOp = spv::OpFAdd;
3446 else
3447 binOp = spv::OpIAdd;
3448 break;
3449 case glslang::EOpSub:
3450 case glslang::EOpSubAssign:
3451 if (isFloat)
3452 binOp = spv::OpFSub;
3453 else
3454 binOp = spv::OpISub;
3455 break;
3456 case glslang::EOpMul:
3457 case glslang::EOpMulAssign:
3458 if (isFloat)
3459 binOp = spv::OpFMul;
3460 else
3461 binOp = spv::OpIMul;
3462 break;
3463 case glslang::EOpVectorTimesScalar:
3464 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003465 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003466 if (builder.isVector(right))
3467 std::swap(left, right);
3468 assert(builder.isScalar(right));
3469 needMatchingVectors = false;
3470 binOp = spv::OpVectorTimesScalar;
3471 } else
3472 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003473 break;
3474 case glslang::EOpVectorTimesMatrix:
3475 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003476 binOp = spv::OpVectorTimesMatrix;
3477 break;
3478 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003479 binOp = spv::OpMatrixTimesVector;
3480 break;
3481 case glslang::EOpMatrixTimesScalar:
3482 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003483 binOp = spv::OpMatrixTimesScalar;
3484 break;
3485 case glslang::EOpMatrixTimesMatrix:
3486 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003487 binOp = spv::OpMatrixTimesMatrix;
3488 break;
3489 case glslang::EOpOuterProduct:
3490 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003491 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003492 break;
3493
3494 case glslang::EOpDiv:
3495 case glslang::EOpDivAssign:
3496 if (isFloat)
3497 binOp = spv::OpFDiv;
3498 else if (isUnsigned)
3499 binOp = spv::OpUDiv;
3500 else
3501 binOp = spv::OpSDiv;
3502 break;
3503 case glslang::EOpMod:
3504 case glslang::EOpModAssign:
3505 if (isFloat)
3506 binOp = spv::OpFMod;
3507 else if (isUnsigned)
3508 binOp = spv::OpUMod;
3509 else
3510 binOp = spv::OpSMod;
3511 break;
3512 case glslang::EOpRightShift:
3513 case glslang::EOpRightShiftAssign:
3514 if (isUnsigned)
3515 binOp = spv::OpShiftRightLogical;
3516 else
3517 binOp = spv::OpShiftRightArithmetic;
3518 break;
3519 case glslang::EOpLeftShift:
3520 case glslang::EOpLeftShiftAssign:
3521 binOp = spv::OpShiftLeftLogical;
3522 break;
3523 case glslang::EOpAnd:
3524 case glslang::EOpAndAssign:
3525 binOp = spv::OpBitwiseAnd;
3526 break;
3527 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003528 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003529 binOp = spv::OpLogicalAnd;
3530 break;
3531 case glslang::EOpInclusiveOr:
3532 case glslang::EOpInclusiveOrAssign:
3533 binOp = spv::OpBitwiseOr;
3534 break;
3535 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003536 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003537 binOp = spv::OpLogicalOr;
3538 break;
3539 case glslang::EOpExclusiveOr:
3540 case glslang::EOpExclusiveOrAssign:
3541 binOp = spv::OpBitwiseXor;
3542 break;
3543 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003544 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003545 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003546 break;
3547
3548 case glslang::EOpLessThan:
3549 case glslang::EOpGreaterThan:
3550 case glslang::EOpLessThanEqual:
3551 case glslang::EOpGreaterThanEqual:
3552 case glslang::EOpEqual:
3553 case glslang::EOpNotEqual:
3554 case glslang::EOpVectorEqual:
3555 case glslang::EOpVectorNotEqual:
3556 comparison = true;
3557 break;
3558 default:
3559 break;
3560 }
3561
John Kessenich7c1aa102015-10-15 13:29:11 -06003562 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003563 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003564 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003565 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003566 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003567
3568 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003569 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003570 builder.promoteScalar(precision, left, right);
3571
qining25262b32016-05-06 17:25:16 -04003572 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3573 addDecoration(result, noContraction);
3574 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003575 }
3576
3577 if (! comparison)
3578 return 0;
3579
John Kessenich7c1aa102015-10-15 13:29:11 -06003580 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003581
John Kessenich4583b612016-08-07 19:14:22 -06003582 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3583 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003584 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003585
3586 switch (op) {
3587 case glslang::EOpLessThan:
3588 if (isFloat)
3589 binOp = spv::OpFOrdLessThan;
3590 else if (isUnsigned)
3591 binOp = spv::OpULessThan;
3592 else
3593 binOp = spv::OpSLessThan;
3594 break;
3595 case glslang::EOpGreaterThan:
3596 if (isFloat)
3597 binOp = spv::OpFOrdGreaterThan;
3598 else if (isUnsigned)
3599 binOp = spv::OpUGreaterThan;
3600 else
3601 binOp = spv::OpSGreaterThan;
3602 break;
3603 case glslang::EOpLessThanEqual:
3604 if (isFloat)
3605 binOp = spv::OpFOrdLessThanEqual;
3606 else if (isUnsigned)
3607 binOp = spv::OpULessThanEqual;
3608 else
3609 binOp = spv::OpSLessThanEqual;
3610 break;
3611 case glslang::EOpGreaterThanEqual:
3612 if (isFloat)
3613 binOp = spv::OpFOrdGreaterThanEqual;
3614 else if (isUnsigned)
3615 binOp = spv::OpUGreaterThanEqual;
3616 else
3617 binOp = spv::OpSGreaterThanEqual;
3618 break;
3619 case glslang::EOpEqual:
3620 case glslang::EOpVectorEqual:
3621 if (isFloat)
3622 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003623 else if (isBool)
3624 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003625 else
3626 binOp = spv::OpIEqual;
3627 break;
3628 case glslang::EOpNotEqual:
3629 case glslang::EOpVectorNotEqual:
3630 if (isFloat)
3631 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003632 else if (isBool)
3633 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003634 else
3635 binOp = spv::OpINotEqual;
3636 break;
3637 default:
3638 break;
3639 }
3640
qining25262b32016-05-06 17:25:16 -04003641 if (binOp != spv::OpNop) {
3642 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3643 addDecoration(result, noContraction);
3644 return builder.setPrecision(result, precision);
3645 }
John Kessenich140f3df2015-06-26 16:58:36 -06003646
3647 return 0;
3648}
3649
John Kessenich04bb8a02015-12-12 12:28:14 -07003650//
3651// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3652// These can be any of:
3653//
3654// matrix * scalar
3655// scalar * matrix
3656// matrix * matrix linear algebraic
3657// matrix * vector
3658// vector * matrix
3659// matrix * matrix componentwise
3660// matrix op matrix op in {+, -, /}
3661// matrix op scalar op in {+, -, /}
3662// scalar op matrix op in {+, -, /}
3663//
qining25262b32016-05-06 17:25:16 -04003664spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07003665{
3666 bool firstClass = true;
3667
3668 // First, handle first-class matrix operations (* and matrix/scalar)
3669 switch (op) {
3670 case spv::OpFDiv:
3671 if (builder.isMatrix(left) && builder.isScalar(right)) {
3672 // turn matrix / scalar into a multiply...
3673 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3674 op = spv::OpMatrixTimesScalar;
3675 } else
3676 firstClass = false;
3677 break;
3678 case spv::OpMatrixTimesScalar:
3679 if (builder.isMatrix(right))
3680 std::swap(left, right);
3681 assert(builder.isScalar(right));
3682 break;
3683 case spv::OpVectorTimesMatrix:
3684 assert(builder.isVector(left));
3685 assert(builder.isMatrix(right));
3686 break;
3687 case spv::OpMatrixTimesVector:
3688 assert(builder.isMatrix(left));
3689 assert(builder.isVector(right));
3690 break;
3691 case spv::OpMatrixTimesMatrix:
3692 assert(builder.isMatrix(left));
3693 assert(builder.isMatrix(right));
3694 break;
3695 default:
3696 firstClass = false;
3697 break;
3698 }
3699
qining25262b32016-05-06 17:25:16 -04003700 if (firstClass) {
3701 spv::Id result = builder.createBinOp(op, typeId, left, right);
3702 addDecoration(result, noContraction);
3703 return builder.setPrecision(result, precision);
3704 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003705
LoopDawg592860c2016-06-09 08:57:35 -06003706 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003707 // The result type of all of them is the same type as the (a) matrix operand.
3708 // The algorithm is to:
3709 // - break the matrix(es) into vectors
3710 // - smear any scalar to a vector
3711 // - do vector operations
3712 // - make a matrix out the vector results
3713 switch (op) {
3714 case spv::OpFAdd:
3715 case spv::OpFSub:
3716 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003717 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003718 case spv::OpFMul:
3719 {
3720 // one time set up...
3721 bool leftMat = builder.isMatrix(left);
3722 bool rightMat = builder.isMatrix(right);
3723 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3724 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3725 spv::Id scalarType = builder.getScalarTypeId(typeId);
3726 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3727 std::vector<spv::Id> results;
3728 spv::Id smearVec = spv::NoResult;
3729 if (builder.isScalar(left))
3730 smearVec = builder.smearScalar(precision, left, vecType);
3731 else if (builder.isScalar(right))
3732 smearVec = builder.smearScalar(precision, right, vecType);
3733
3734 // do each vector op
3735 for (unsigned int c = 0; c < numCols; ++c) {
3736 std::vector<unsigned int> indexes;
3737 indexes.push_back(c);
3738 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3739 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003740 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3741 addDecoration(result, noContraction);
3742 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003743 }
3744
3745 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003746 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003747 }
3748 default:
3749 assert(0);
3750 return spv::NoResult;
3751 }
3752}
3753
qining25262b32016-05-06 17:25:16 -04003754spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06003755{
3756 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003757 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003758 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003759 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003760#ifdef AMD_EXTENSIONS
3761 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3762#else
Rex Xu04db3f52015-09-16 11:44:02 +08003763 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003764#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003765
3766 switch (op) {
3767 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003768 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003769 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003770 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003771 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003772 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003773 unaryOp = spv::OpSNegate;
3774 break;
3775
3776 case glslang::EOpLogicalNot:
3777 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003778 unaryOp = spv::OpLogicalNot;
3779 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003780 case glslang::EOpBitwiseNot:
3781 unaryOp = spv::OpNot;
3782 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003783
John Kessenich140f3df2015-06-26 16:58:36 -06003784 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003785 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003786 break;
3787 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003788 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003789 break;
3790 case glslang::EOpTranspose:
3791 unaryOp = spv::OpTranspose;
3792 break;
3793
3794 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003795 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003796 break;
3797 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003798 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003799 break;
3800 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003801 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003802 break;
3803 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003804 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003805 break;
3806 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003807 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003808 break;
3809 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003810 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003811 break;
3812 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003813 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003814 break;
3815 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003816 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003817 break;
3818
3819 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003820 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003821 break;
3822 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003823 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003824 break;
3825 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003826 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003827 break;
3828 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003829 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003830 break;
3831 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003832 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003833 break;
3834 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003835 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003836 break;
3837
3838 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003839 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003840 break;
3841 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003842 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003843 break;
3844
3845 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003846 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003847 break;
3848 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003849 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003850 break;
3851 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003852 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003853 break;
3854 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003855 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003856 break;
3857 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003858 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003859 break;
3860 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003861 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003862 break;
3863
3864 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003865 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003866 break;
3867 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003868 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003869 break;
3870 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003871 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003872 break;
3873 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003874 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003875 break;
3876 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003877 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003878 break;
3879 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003880 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003881 break;
3882
3883 case glslang::EOpIsNan:
3884 unaryOp = spv::OpIsNan;
3885 break;
3886 case glslang::EOpIsInf:
3887 unaryOp = spv::OpIsInf;
3888 break;
LoopDawg592860c2016-06-09 08:57:35 -06003889 case glslang::EOpIsFinite:
3890 unaryOp = spv::OpIsFinite;
3891 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003892
Rex Xucbc426e2015-12-15 16:03:10 +08003893 case glslang::EOpFloatBitsToInt:
3894 case glslang::EOpFloatBitsToUint:
3895 case glslang::EOpIntBitsToFloat:
3896 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003897 case glslang::EOpDoubleBitsToInt64:
3898 case glslang::EOpDoubleBitsToUint64:
3899 case glslang::EOpInt64BitsToDouble:
3900 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003901 unaryOp = spv::OpBitcast;
3902 break;
3903
John Kessenich140f3df2015-06-26 16:58:36 -06003904 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003905 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003906 break;
3907 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003908 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003909 break;
3910 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003911 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003912 break;
3913 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003914 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003915 break;
3916 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003917 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003918 break;
3919 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003920 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003921 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003922 case glslang::EOpPackSnorm4x8:
3923 libCall = spv::GLSLstd450PackSnorm4x8;
3924 break;
3925 case glslang::EOpUnpackSnorm4x8:
3926 libCall = spv::GLSLstd450UnpackSnorm4x8;
3927 break;
3928 case glslang::EOpPackUnorm4x8:
3929 libCall = spv::GLSLstd450PackUnorm4x8;
3930 break;
3931 case glslang::EOpUnpackUnorm4x8:
3932 libCall = spv::GLSLstd450UnpackUnorm4x8;
3933 break;
3934 case glslang::EOpPackDouble2x32:
3935 libCall = spv::GLSLstd450PackDouble2x32;
3936 break;
3937 case glslang::EOpUnpackDouble2x32:
3938 libCall = spv::GLSLstd450UnpackDouble2x32;
3939 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003940
Rex Xu8ff43de2016-04-22 16:51:45 +08003941 case glslang::EOpPackInt2x32:
3942 case glslang::EOpUnpackInt2x32:
3943 case glslang::EOpPackUint2x32:
3944 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003945 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003946 break;
3947
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003948#ifdef AMD_EXTENSIONS
3949 case glslang::EOpPackFloat2x16:
3950 case glslang::EOpUnpackFloat2x16:
3951 unaryOp = spv::OpBitcast;
3952 break;
3953#endif
3954
John Kessenich140f3df2015-06-26 16:58:36 -06003955 case glslang::EOpDPdx:
3956 unaryOp = spv::OpDPdx;
3957 break;
3958 case glslang::EOpDPdy:
3959 unaryOp = spv::OpDPdy;
3960 break;
3961 case glslang::EOpFwidth:
3962 unaryOp = spv::OpFwidth;
3963 break;
3964 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003965 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003966 unaryOp = spv::OpDPdxFine;
3967 break;
3968 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003969 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003970 unaryOp = spv::OpDPdyFine;
3971 break;
3972 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003973 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003974 unaryOp = spv::OpFwidthFine;
3975 break;
3976 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003977 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003978 unaryOp = spv::OpDPdxCoarse;
3979 break;
3980 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003981 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003982 unaryOp = spv::OpDPdyCoarse;
3983 break;
3984 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003985 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003986 unaryOp = spv::OpFwidthCoarse;
3987 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003988 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003989 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003990 libCall = spv::GLSLstd450InterpolateAtCentroid;
3991 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003992 case glslang::EOpAny:
3993 unaryOp = spv::OpAny;
3994 break;
3995 case glslang::EOpAll:
3996 unaryOp = spv::OpAll;
3997 break;
3998
3999 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004000 if (isFloat)
4001 libCall = spv::GLSLstd450FAbs;
4002 else
4003 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004004 break;
4005 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004006 if (isFloat)
4007 libCall = spv::GLSLstd450FSign;
4008 else
4009 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004010 break;
4011
John Kessenichfc51d282015-08-19 13:34:18 -06004012 case glslang::EOpAtomicCounterIncrement:
4013 case glslang::EOpAtomicCounterDecrement:
4014 case glslang::EOpAtomicCounter:
4015 {
4016 // Handle all of the atomics in one place, in createAtomicOperation()
4017 std::vector<spv::Id> operands;
4018 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004019 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004020 }
4021
John Kessenichfc51d282015-08-19 13:34:18 -06004022 case glslang::EOpBitFieldReverse:
4023 unaryOp = spv::OpBitReverse;
4024 break;
4025 case glslang::EOpBitCount:
4026 unaryOp = spv::OpBitCount;
4027 break;
4028 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004029 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004030 break;
4031 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004032 if (isUnsigned)
4033 libCall = spv::GLSLstd450FindUMsb;
4034 else
4035 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004036 break;
4037
Rex Xu574ab042016-04-14 16:53:07 +08004038 case glslang::EOpBallot:
4039 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004040 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004041 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004042 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004043#ifdef AMD_EXTENSIONS
4044 case glslang::EOpMinInvocations:
4045 case glslang::EOpMaxInvocations:
4046 case glslang::EOpAddInvocations:
4047 case glslang::EOpMinInvocationsNonUniform:
4048 case glslang::EOpMaxInvocationsNonUniform:
4049 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004050 case glslang::EOpMinInvocationsInclusiveScan:
4051 case glslang::EOpMaxInvocationsInclusiveScan:
4052 case glslang::EOpAddInvocationsInclusiveScan:
4053 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4054 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4055 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4056 case glslang::EOpMinInvocationsExclusiveScan:
4057 case glslang::EOpMaxInvocationsExclusiveScan:
4058 case glslang::EOpAddInvocationsExclusiveScan:
4059 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4060 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4061 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004062#endif
Rex Xu51596642016-09-21 18:56:12 +08004063 {
4064 std::vector<spv::Id> operands;
4065 operands.push_back(operand);
4066 return createInvocationsOperation(op, typeId, operands, typeProxy);
4067 }
Rex Xu9d93a232016-05-05 12:30:44 +08004068
4069#ifdef AMD_EXTENSIONS
4070 case glslang::EOpMbcnt:
4071 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4072 libCall = spv::MbcntAMD;
4073 break;
4074
4075 case glslang::EOpCubeFaceIndex:
4076 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4077 libCall = spv::CubeFaceIndexAMD;
4078 break;
4079
4080 case glslang::EOpCubeFaceCoord:
4081 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4082 libCall = spv::CubeFaceCoordAMD;
4083 break;
4084#endif
Rex Xu338b1852016-05-05 20:38:33 +08004085
John Kessenich140f3df2015-06-26 16:58:36 -06004086 default:
4087 return 0;
4088 }
4089
4090 spv::Id id;
4091 if (libCall >= 0) {
4092 std::vector<spv::Id> args;
4093 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004094 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004095 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004096 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004097 }
John Kessenich140f3df2015-06-26 16:58:36 -06004098
qining25262b32016-05-06 17:25:16 -04004099 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004100 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004101}
4102
John Kessenich7a53f762016-01-20 11:19:27 -07004103// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004104spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07004105{
4106 // Handle unary operations vector by vector.
4107 // The result type is the same type as the original type.
4108 // The algorithm is to:
4109 // - break the matrix into vectors
4110 // - apply the operation to each vector
4111 // - make a matrix out the vector results
4112
4113 // get the types sorted out
4114 int numCols = builder.getNumColumns(operand);
4115 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004116 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4117 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004118 std::vector<spv::Id> results;
4119
4120 // do each vector op
4121 for (int c = 0; c < numCols; ++c) {
4122 std::vector<unsigned int> indexes;
4123 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004124 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4125 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4126 addDecoration(destVec, noContraction);
4127 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004128 }
4129
4130 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004131 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004132}
4133
Rex Xu73e3ce72016-04-27 18:48:17 +08004134spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destType, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004135{
4136 spv::Op convOp = spv::OpNop;
4137 spv::Id zero = 0;
4138 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004139 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004140
4141 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4142
4143 switch (op) {
4144 case glslang::EOpConvIntToBool:
4145 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004146 case glslang::EOpConvInt64ToBool:
4147 case glslang::EOpConvUint64ToBool:
4148 zero = (op == glslang::EOpConvInt64ToBool ||
4149 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004150 zero = makeSmearedConstant(zero, vectorSize);
4151 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4152
4153 case glslang::EOpConvFloatToBool:
4154 zero = builder.makeFloatConstant(0.0F);
4155 zero = makeSmearedConstant(zero, vectorSize);
4156 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4157
4158 case glslang::EOpConvDoubleToBool:
4159 zero = builder.makeDoubleConstant(0.0);
4160 zero = makeSmearedConstant(zero, vectorSize);
4161 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4162
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004163#ifdef AMD_EXTENSIONS
4164 case glslang::EOpConvFloat16ToBool:
4165 zero = builder.makeFloat16Constant(0.0F);
4166 zero = makeSmearedConstant(zero, vectorSize);
4167 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4168#endif
4169
John Kessenich140f3df2015-06-26 16:58:36 -06004170 case glslang::EOpConvBoolToFloat:
4171 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004172 zero = builder.makeFloatConstant(0.0F);
4173 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004174 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004175
John Kessenich140f3df2015-06-26 16:58:36 -06004176 case glslang::EOpConvBoolToDouble:
4177 convOp = spv::OpSelect;
4178 zero = builder.makeDoubleConstant(0.0);
4179 one = builder.makeDoubleConstant(1.0);
4180 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004181
4182#ifdef AMD_EXTENSIONS
4183 case glslang::EOpConvBoolToFloat16:
4184 convOp = spv::OpSelect;
4185 zero = builder.makeFloat16Constant(0.0F);
4186 one = builder.makeFloat16Constant(1.0F);
4187 break;
4188#endif
4189
John Kessenich140f3df2015-06-26 16:58:36 -06004190 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004191 case glslang::EOpConvBoolToInt64:
4192 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4193 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004194 convOp = spv::OpSelect;
4195 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004196
John Kessenich140f3df2015-06-26 16:58:36 -06004197 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004198 case glslang::EOpConvBoolToUint64:
4199 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4200 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004201 convOp = spv::OpSelect;
4202 break;
4203
4204 case glslang::EOpConvIntToFloat:
4205 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004206 case glslang::EOpConvInt64ToFloat:
4207 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004208#ifdef AMD_EXTENSIONS
4209 case glslang::EOpConvIntToFloat16:
4210 case glslang::EOpConvInt64ToFloat16:
4211#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004212 convOp = spv::OpConvertSToF;
4213 break;
4214
4215 case glslang::EOpConvUintToFloat:
4216 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004217 case glslang::EOpConvUint64ToFloat:
4218 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004219#ifdef AMD_EXTENSIONS
4220 case glslang::EOpConvUintToFloat16:
4221 case glslang::EOpConvUint64ToFloat16:
4222#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004223 convOp = spv::OpConvertUToF;
4224 break;
4225
4226 case glslang::EOpConvDoubleToFloat:
4227 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004228#ifdef AMD_EXTENSIONS
4229 case glslang::EOpConvDoubleToFloat16:
4230 case glslang::EOpConvFloat16ToDouble:
4231 case glslang::EOpConvFloatToFloat16:
4232 case glslang::EOpConvFloat16ToFloat:
4233#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004234 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004235 if (builder.isMatrixType(destType))
4236 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004237 break;
4238
4239 case glslang::EOpConvFloatToInt:
4240 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004241 case glslang::EOpConvFloatToInt64:
4242 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004243#ifdef AMD_EXTENSIONS
4244 case glslang::EOpConvFloat16ToInt:
4245 case glslang::EOpConvFloat16ToInt64:
4246#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004247 convOp = spv::OpConvertFToS;
4248 break;
4249
4250 case glslang::EOpConvUintToInt:
4251 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004252 case glslang::EOpConvUint64ToInt64:
4253 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004254 if (builder.isInSpecConstCodeGenMode()) {
4255 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004256 zero = (op == glslang::EOpConvUint64ToInt64 ||
4257 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004258 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004259 // Use OpIAdd, instead of OpBitcast to do the conversion when
4260 // generating for OpSpecConstantOp instruction.
4261 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4262 }
4263 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004264 convOp = spv::OpBitcast;
4265 break;
4266
4267 case glslang::EOpConvFloatToUint:
4268 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004269 case glslang::EOpConvFloatToUint64:
4270 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004271#ifdef AMD_EXTENSIONS
4272 case glslang::EOpConvFloat16ToUint:
4273 case glslang::EOpConvFloat16ToUint64:
4274#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004275 convOp = spv::OpConvertFToU;
4276 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004277
4278 case glslang::EOpConvIntToInt64:
4279 case glslang::EOpConvInt64ToInt:
4280 convOp = spv::OpSConvert;
4281 break;
4282
4283 case glslang::EOpConvUintToUint64:
4284 case glslang::EOpConvUint64ToUint:
4285 convOp = spv::OpUConvert;
4286 break;
4287
4288 case glslang::EOpConvIntToUint64:
4289 case glslang::EOpConvInt64ToUint:
4290 case glslang::EOpConvUint64ToInt:
4291 case glslang::EOpConvUintToInt64:
4292 // OpSConvert/OpUConvert + OpBitCast
4293 switch (op) {
4294 case glslang::EOpConvIntToUint64:
4295 convOp = spv::OpSConvert;
4296 type = builder.makeIntType(64);
4297 break;
4298 case glslang::EOpConvInt64ToUint:
4299 convOp = spv::OpSConvert;
4300 type = builder.makeIntType(32);
4301 break;
4302 case glslang::EOpConvUint64ToInt:
4303 convOp = spv::OpUConvert;
4304 type = builder.makeUintType(32);
4305 break;
4306 case glslang::EOpConvUintToInt64:
4307 convOp = spv::OpUConvert;
4308 type = builder.makeUintType(64);
4309 break;
4310 default:
4311 assert(0);
4312 break;
4313 }
4314
4315 if (vectorSize > 0)
4316 type = builder.makeVectorType(type, vectorSize);
4317
4318 operand = builder.createUnaryOp(convOp, type, operand);
4319
4320 if (builder.isInSpecConstCodeGenMode()) {
4321 // Build zero scalar or vector for OpIAdd.
4322 zero = (op == glslang::EOpConvIntToUint64 ||
4323 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4324 zero = makeSmearedConstant(zero, vectorSize);
4325 // Use OpIAdd, instead of OpBitcast to do the conversion when
4326 // generating for OpSpecConstantOp instruction.
4327 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4328 }
4329 // For normal run-time conversion instruction, use OpBitcast.
4330 convOp = spv::OpBitcast;
4331 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004332 default:
4333 break;
4334 }
4335
4336 spv::Id result = 0;
4337 if (convOp == spv::OpNop)
4338 return result;
4339
4340 if (convOp == spv::OpSelect) {
4341 zero = makeSmearedConstant(zero, vectorSize);
4342 one = makeSmearedConstant(one, vectorSize);
4343 result = builder.createTriOp(convOp, destType, operand, one, zero);
4344 } else
4345 result = builder.createUnaryOp(convOp, destType, operand);
4346
John Kessenich32cfd492016-02-02 12:37:46 -07004347 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004348}
4349
4350spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4351{
4352 if (vectorSize == 0)
4353 return constant;
4354
4355 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4356 std::vector<spv::Id> components;
4357 for (int c = 0; c < vectorSize; ++c)
4358 components.push_back(constant);
4359 return builder.makeCompositeConstant(vectorTypeId, components);
4360}
4361
John Kessenich426394d2015-07-23 10:22:48 -06004362// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004363spv::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 -06004364{
4365 spv::Op opCode = spv::OpNop;
4366
4367 switch (op) {
4368 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004369 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004370 opCode = spv::OpAtomicIAdd;
4371 break;
4372 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004373 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004374 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004375 break;
4376 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004377 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004378 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004379 break;
4380 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004381 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004382 opCode = spv::OpAtomicAnd;
4383 break;
4384 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004385 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004386 opCode = spv::OpAtomicOr;
4387 break;
4388 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004389 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004390 opCode = spv::OpAtomicXor;
4391 break;
4392 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004393 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004394 opCode = spv::OpAtomicExchange;
4395 break;
4396 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004397 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004398 opCode = spv::OpAtomicCompareExchange;
4399 break;
4400 case glslang::EOpAtomicCounterIncrement:
4401 opCode = spv::OpAtomicIIncrement;
4402 break;
4403 case glslang::EOpAtomicCounterDecrement:
4404 opCode = spv::OpAtomicIDecrement;
4405 break;
4406 case glslang::EOpAtomicCounter:
4407 opCode = spv::OpAtomicLoad;
4408 break;
4409 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004410 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004411 break;
4412 }
4413
4414 // Sort out the operands
4415 // - mapping from glslang -> SPV
4416 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004417 // - compare-exchange swaps the value and comparator
4418 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004419 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4420 auto opIt = operands.begin(); // walk the glslang operands
4421 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004422 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4423 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4424 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004425 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4426 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004427 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004428 spvAtomicOperands.push_back(*(opIt + 1));
4429 spvAtomicOperands.push_back(*opIt);
4430 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004431 }
John Kessenich426394d2015-07-23 10:22:48 -06004432
John Kessenich3e60a6f2015-09-14 22:45:16 -06004433 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004434 for (; opIt != operands.end(); ++opIt)
4435 spvAtomicOperands.push_back(*opIt);
4436
4437 return builder.createOp(opCode, typeId, spvAtomicOperands);
4438}
4439
John Kessenich91cef522016-05-05 16:45:40 -06004440// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004441spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004442{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004443#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004444 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004445 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004446#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004447
Rex Xu51596642016-09-21 18:56:12 +08004448 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004449 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004450 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4451
chaocf200da82016-12-20 12:44:35 -08004452 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4453 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004454 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4455 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004456 } else if (op == glslang::EOpAnyInvocation ||
4457 op == glslang::EOpAllInvocations ||
4458 op == glslang::EOpAllInvocationsEqual) {
4459 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4460 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004461 } else {
4462 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004463#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004464 if (op == glslang::EOpMinInvocationsNonUniform ||
4465 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004466 op == glslang::EOpAddInvocationsNonUniform ||
4467 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4468 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4469 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4470 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4471 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4472 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004473 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004474#endif
Rex Xu51596642016-09-21 18:56:12 +08004475
4476 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004477#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004478 switch (op) {
4479 case glslang::EOpMinInvocations:
4480 case glslang::EOpMaxInvocations:
4481 case glslang::EOpAddInvocations:
4482 case glslang::EOpMinInvocationsNonUniform:
4483 case glslang::EOpMaxInvocationsNonUniform:
4484 case glslang::EOpAddInvocationsNonUniform:
4485 groupOperation = spv::GroupOperationReduce;
4486 spvGroupOperands.push_back(groupOperation);
4487 break;
4488 case glslang::EOpMinInvocationsInclusiveScan:
4489 case glslang::EOpMaxInvocationsInclusiveScan:
4490 case glslang::EOpAddInvocationsInclusiveScan:
4491 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4492 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4493 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4494 groupOperation = spv::GroupOperationInclusiveScan;
4495 spvGroupOperands.push_back(groupOperation);
4496 break;
4497 case glslang::EOpMinInvocationsExclusiveScan:
4498 case glslang::EOpMaxInvocationsExclusiveScan:
4499 case glslang::EOpAddInvocationsExclusiveScan:
4500 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4501 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4502 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4503 groupOperation = spv::GroupOperationExclusiveScan;
4504 spvGroupOperands.push_back(groupOperation);
4505 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004506 default:
4507 break;
Rex Xu430ef402016-10-14 17:22:23 +08004508 }
Rex Xu9d93a232016-05-05 12:30:44 +08004509#endif
Rex Xu51596642016-09-21 18:56:12 +08004510 }
4511
4512 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4513 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004514
4515 switch (op) {
4516 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004517 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004518 break;
John Kessenich91cef522016-05-05 16:45:40 -06004519 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004520 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004521 break;
John Kessenich91cef522016-05-05 16:45:40 -06004522 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004523 opCode = spv::OpSubgroupAllEqualKHR;
4524 break;
Rex Xu51596642016-09-21 18:56:12 +08004525 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004526 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004527 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004528 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004529 break;
4530 case glslang::EOpReadFirstInvocation:
4531 opCode = spv::OpSubgroupFirstInvocationKHR;
4532 break;
4533 case glslang::EOpBallot:
4534 {
4535 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4536 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4537 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4538 //
4539 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4540 //
4541 spv::Id uintType = builder.makeUintType(32);
4542 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4543 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4544
4545 std::vector<spv::Id> components;
4546 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4547 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4548
4549 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4550 return builder.createUnaryOp(spv::OpBitcast, typeId,
4551 builder.createCompositeConstruct(uvec2Type, components));
4552 }
4553
Rex Xu9d93a232016-05-05 12:30:44 +08004554#ifdef AMD_EXTENSIONS
4555 case glslang::EOpMinInvocations:
4556 case glslang::EOpMaxInvocations:
4557 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004558 case glslang::EOpMinInvocationsInclusiveScan:
4559 case glslang::EOpMaxInvocationsInclusiveScan:
4560 case glslang::EOpAddInvocationsInclusiveScan:
4561 case glslang::EOpMinInvocationsExclusiveScan:
4562 case glslang::EOpMaxInvocationsExclusiveScan:
4563 case glslang::EOpAddInvocationsExclusiveScan:
4564 if (op == glslang::EOpMinInvocations ||
4565 op == glslang::EOpMinInvocationsInclusiveScan ||
4566 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004567 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004568 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004569 else {
4570 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004571 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004572 else
Rex Xu51596642016-09-21 18:56:12 +08004573 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004574 }
Rex Xu430ef402016-10-14 17:22:23 +08004575 } else if (op == glslang::EOpMaxInvocations ||
4576 op == glslang::EOpMaxInvocationsInclusiveScan ||
4577 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004578 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004579 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004580 else {
4581 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004582 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004583 else
Rex Xu51596642016-09-21 18:56:12 +08004584 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004585 }
4586 } else {
4587 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004588 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004589 else
Rex Xu51596642016-09-21 18:56:12 +08004590 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004591 }
4592
Rex Xu2bbbe062016-08-23 15:41:05 +08004593 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004594 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004595
4596 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004597 case glslang::EOpMinInvocationsNonUniform:
4598 case glslang::EOpMaxInvocationsNonUniform:
4599 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004600 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4601 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4602 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4603 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4604 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4605 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4606 if (op == glslang::EOpMinInvocationsNonUniform ||
4607 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4608 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004609 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004610 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004611 else {
4612 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004613 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004614 else
Rex Xu51596642016-09-21 18:56:12 +08004615 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004616 }
4617 }
Rex Xu430ef402016-10-14 17:22:23 +08004618 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4619 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4620 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004621 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004622 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004623 else {
4624 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004625 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004626 else
Rex Xu51596642016-09-21 18:56:12 +08004627 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004628 }
4629 }
4630 else {
4631 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004632 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004633 else
Rex Xu51596642016-09-21 18:56:12 +08004634 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004635 }
4636
Rex Xu2bbbe062016-08-23 15:41:05 +08004637 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004638 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004639
4640 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004641#endif
John Kessenich91cef522016-05-05 16:45:40 -06004642 default:
4643 logger->missingFunctionality("invocation operation");
4644 return spv::NoResult;
4645 }
Rex Xu51596642016-09-21 18:56:12 +08004646
4647 assert(opCode != spv::OpNop);
4648 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004649}
4650
Rex Xu2bbbe062016-08-23 15:41:05 +08004651// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004652spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004653{
Rex Xub7072052016-09-26 15:53:40 +08004654#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004655 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4656 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004657 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004658 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004659 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4660 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4661 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004662#else
4663 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4664 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004665 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4666 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004667#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004668
4669 // Handle group invocation operations scalar by scalar.
4670 // The result type is the same type as the original type.
4671 // The algorithm is to:
4672 // - break the vector into scalars
4673 // - apply the operation to each scalar
4674 // - make a vector out the scalar results
4675
4676 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004677 int numComponents = builder.getNumComponents(operands[0]);
4678 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004679 std::vector<spv::Id> results;
4680
4681 // do each scalar op
4682 for (int comp = 0; comp < numComponents; ++comp) {
4683 std::vector<unsigned int> indexes;
4684 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004685 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004686 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004687 if (op == spv::OpSubgroupReadInvocationKHR) {
4688 spvGroupOperands.push_back(scalar);
4689 spvGroupOperands.push_back(operands[1]);
4690 } else if (op == spv::OpGroupBroadcast) {
4691 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004692 spvGroupOperands.push_back(scalar);
4693 spvGroupOperands.push_back(operands[1]);
4694 } else {
chaocf200da82016-12-20 12:44:35 -08004695 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004696 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004697 spvGroupOperands.push_back(scalar);
4698 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004699
Rex Xub7072052016-09-26 15:53:40 +08004700 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004701 }
4702
4703 // put the pieces together
4704 return builder.createCompositeConstruct(typeId, results);
4705}
Rex Xu2bbbe062016-08-23 15:41:05 +08004706
John Kessenich5e4b1242015-08-06 22:53:06 -06004707spv::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 -06004708{
Rex Xu8ff43de2016-04-22 16:51:45 +08004709 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004710#ifdef AMD_EXTENSIONS
4711 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4712#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004713 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004714#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004715
John Kessenich140f3df2015-06-26 16:58:36 -06004716 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004717 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004718 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004719 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004720 spv::Id typeId0 = 0;
4721 if (consumedOperands > 0)
4722 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08004723 spv::Id typeId1 = 0;
4724 if (consumedOperands > 1)
4725 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07004726 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004727
4728 switch (op) {
4729 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004730 if (isFloat)
4731 libCall = spv::GLSLstd450FMin;
4732 else if (isUnsigned)
4733 libCall = spv::GLSLstd450UMin;
4734 else
4735 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004736 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004737 break;
4738 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004739 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004740 break;
4741 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004742 if (isFloat)
4743 libCall = spv::GLSLstd450FMax;
4744 else if (isUnsigned)
4745 libCall = spv::GLSLstd450UMax;
4746 else
4747 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004748 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004749 break;
4750 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004751 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004752 break;
4753 case glslang::EOpDot:
4754 opCode = spv::OpDot;
4755 break;
4756 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004757 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004758 break;
4759
4760 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004761 if (isFloat)
4762 libCall = spv::GLSLstd450FClamp;
4763 else if (isUnsigned)
4764 libCall = spv::GLSLstd450UClamp;
4765 else
4766 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004767 builder.promoteScalar(precision, operands.front(), operands[1]);
4768 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004769 break;
4770 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004771 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4772 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004773 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004774 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004775 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004776 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004777 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004778 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004779 break;
4780 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004781 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004782 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004783 break;
4784 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004785 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004786 builder.promoteScalar(precision, operands[0], operands[2]);
4787 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004788 break;
4789
4790 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004791 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004792 break;
4793 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004794 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004795 break;
4796 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004797 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004798 break;
4799 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004800 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004801 break;
4802 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004803 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004804 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004805 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004806 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004807 libCall = spv::GLSLstd450InterpolateAtSample;
4808 break;
4809 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004810 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004811 libCall = spv::GLSLstd450InterpolateAtOffset;
4812 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004813 case glslang::EOpAddCarry:
4814 opCode = spv::OpIAddCarry;
4815 typeId = builder.makeStructResultType(typeId0, typeId0);
4816 consumedOperands = 2;
4817 break;
4818 case glslang::EOpSubBorrow:
4819 opCode = spv::OpISubBorrow;
4820 typeId = builder.makeStructResultType(typeId0, typeId0);
4821 consumedOperands = 2;
4822 break;
4823 case glslang::EOpUMulExtended:
4824 opCode = spv::OpUMulExtended;
4825 typeId = builder.makeStructResultType(typeId0, typeId0);
4826 consumedOperands = 2;
4827 break;
4828 case glslang::EOpIMulExtended:
4829 opCode = spv::OpSMulExtended;
4830 typeId = builder.makeStructResultType(typeId0, typeId0);
4831 consumedOperands = 2;
4832 break;
4833 case glslang::EOpBitfieldExtract:
4834 if (isUnsigned)
4835 opCode = spv::OpBitFieldUExtract;
4836 else
4837 opCode = spv::OpBitFieldSExtract;
4838 break;
4839 case glslang::EOpBitfieldInsert:
4840 opCode = spv::OpBitFieldInsert;
4841 break;
4842
4843 case glslang::EOpFma:
4844 libCall = spv::GLSLstd450Fma;
4845 break;
4846 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004847 {
4848 libCall = spv::GLSLstd450FrexpStruct;
4849 assert(builder.isPointerType(typeId1));
4850 typeId1 = builder.getContainedTypeId(typeId1);
4851#ifdef AMD_EXTENSIONS
4852 int width = builder.getScalarTypeWidth(typeId1);
4853#else
4854 int width = 32;
4855#endif
4856 if (builder.getNumComponents(operands[0]) == 1)
4857 frexpIntType = builder.makeIntegerType(width, true);
4858 else
4859 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
4860 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4861 consumedOperands = 1;
4862 }
John Kessenich55e7d112015-11-15 21:33:39 -07004863 break;
4864 case glslang::EOpLdexp:
4865 libCall = spv::GLSLstd450Ldexp;
4866 break;
4867
Rex Xu574ab042016-04-14 16:53:07 +08004868 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004869 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004870
Rex Xu9d93a232016-05-05 12:30:44 +08004871#ifdef AMD_EXTENSIONS
4872 case glslang::EOpSwizzleInvocations:
4873 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4874 libCall = spv::SwizzleInvocationsAMD;
4875 break;
4876 case glslang::EOpSwizzleInvocationsMasked:
4877 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4878 libCall = spv::SwizzleInvocationsMaskedAMD;
4879 break;
4880 case glslang::EOpWriteInvocation:
4881 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4882 libCall = spv::WriteInvocationAMD;
4883 break;
4884
4885 case glslang::EOpMin3:
4886 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4887 if (isFloat)
4888 libCall = spv::FMin3AMD;
4889 else {
4890 if (isUnsigned)
4891 libCall = spv::UMin3AMD;
4892 else
4893 libCall = spv::SMin3AMD;
4894 }
4895 break;
4896 case glslang::EOpMax3:
4897 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4898 if (isFloat)
4899 libCall = spv::FMax3AMD;
4900 else {
4901 if (isUnsigned)
4902 libCall = spv::UMax3AMD;
4903 else
4904 libCall = spv::SMax3AMD;
4905 }
4906 break;
4907 case glslang::EOpMid3:
4908 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4909 if (isFloat)
4910 libCall = spv::FMid3AMD;
4911 else {
4912 if (isUnsigned)
4913 libCall = spv::UMid3AMD;
4914 else
4915 libCall = spv::SMid3AMD;
4916 }
4917 break;
4918
4919 case glslang::EOpInterpolateAtVertex:
4920 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4921 libCall = spv::InterpolateAtVertexAMD;
4922 break;
4923#endif
4924
John Kessenich140f3df2015-06-26 16:58:36 -06004925 default:
4926 return 0;
4927 }
4928
4929 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004930 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004931 // Use an extended instruction from the standard library.
4932 // Construct the call arguments, without modifying the original operands vector.
4933 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4934 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004935 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004936 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004937 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004938 case 0:
4939 // should all be handled by visitAggregate and createNoArgOperation
4940 assert(0);
4941 return 0;
4942 case 1:
4943 // should all be handled by createUnaryOperation
4944 assert(0);
4945 return 0;
4946 case 2:
4947 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4948 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004949 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004950 // anything 3 or over doesn't have l-value operands, so all should be consumed
4951 assert(consumedOperands == operands.size());
4952 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004953 break;
4954 }
4955 }
4956
John Kessenich55e7d112015-11-15 21:33:39 -07004957 // Decode the return types that were structures
4958 switch (op) {
4959 case glslang::EOpAddCarry:
4960 case glslang::EOpSubBorrow:
4961 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4962 id = builder.createCompositeExtract(id, typeId0, 0);
4963 break;
4964 case glslang::EOpUMulExtended:
4965 case glslang::EOpIMulExtended:
4966 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4967 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4968 break;
4969 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004970 {
4971 assert(operands.size() == 2);
4972 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
4973 // "exp" is floating-point type (from HLSL intrinsic)
4974 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
4975 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
4976 builder.createStore(member1, operands[1]);
4977 } else
4978 // "exp" is integer type (from GLSL built-in function)
4979 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4980 id = builder.createCompositeExtract(id, typeId0, 0);
4981 }
John Kessenich55e7d112015-11-15 21:33:39 -07004982 break;
4983 default:
4984 break;
4985 }
4986
John Kessenich32cfd492016-02-02 12:37:46 -07004987 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004988}
4989
Rex Xu9d93a232016-05-05 12:30:44 +08004990// Intrinsics with no arguments (or no return value, and no precision).
4991spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004992{
4993 // TODO: get the barrier operands correct
4994
4995 switch (op) {
4996 case glslang::EOpEmitVertex:
4997 builder.createNoResultOp(spv::OpEmitVertex);
4998 return 0;
4999 case glslang::EOpEndPrimitive:
5000 builder.createNoResultOp(spv::OpEndPrimitive);
5001 return 0;
5002 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005003 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005004 return 0;
5005 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005006 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005007 return 0;
5008 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005009 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005010 return 0;
5011 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005012 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005013 return 0;
5014 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005015 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005016 return 0;
5017 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005018 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005019 return 0;
5020 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005021 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005022 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005023 case glslang::EOpAllMemoryBarrierWithGroupSync:
5024 // Control barrier with non-"None" semantic is also a memory barrier.
5025 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5026 return 0;
5027 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5028 // Control barrier with non-"None" semantic is also a memory barrier.
5029 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5030 return 0;
5031 case glslang::EOpWorkgroupMemoryBarrier:
5032 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5033 return 0;
5034 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5035 // Control barrier with non-"None" semantic is also a memory barrier.
5036 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5037 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005038#ifdef AMD_EXTENSIONS
5039 case glslang::EOpTime:
5040 {
5041 std::vector<spv::Id> args; // Dummy arguments
5042 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5043 return builder.setPrecision(id, precision);
5044 }
5045#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005046 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005047 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005048 return 0;
5049 }
5050}
5051
5052spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5053{
John Kessenich2f273362015-07-18 22:34:27 -06005054 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005055 spv::Id id;
5056 if (symbolValues.end() != iter) {
5057 id = iter->second;
5058 return id;
5059 }
5060
5061 // it was not found, create it
5062 id = createSpvVariable(symbol);
5063 symbolValues[symbol->getId()] = id;
5064
Rex Xuc884b4a2016-06-29 15:03:44 +08005065 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005066 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005067 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005068 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005069 if (symbol->getType().getQualifier().hasSpecConstantId())
5070 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005071 if (symbol->getQualifier().hasIndex())
5072 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5073 if (symbol->getQualifier().hasComponent())
5074 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5075 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005076 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005077 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005078 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005079 if (symbol->getQualifier().hasXfbBuffer())
5080 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5081 if (symbol->getQualifier().hasXfbOffset())
5082 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5083 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005084 // atomic counters use this:
5085 if (symbol->getQualifier().hasOffset())
5086 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005087 }
5088
scygan2c864272016-05-18 18:09:17 +02005089 if (symbol->getQualifier().hasLocation())
5090 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005091 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005092 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005093 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005094 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005095 }
John Kessenich140f3df2015-06-26 16:58:36 -06005096 if (symbol->getQualifier().hasSet())
5097 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005098 else if (IsDescriptorResource(symbol->getType())) {
5099 // default to 0
5100 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5101 }
John Kessenich140f3df2015-06-26 16:58:36 -06005102 if (symbol->getQualifier().hasBinding())
5103 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005104 if (symbol->getQualifier().hasAttachment())
5105 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005106 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005107 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005108 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005109 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005110 if (symbol->getQualifier().hasXfbBuffer())
5111 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5112 }
5113
Rex Xu1da878f2016-02-21 20:59:01 +08005114 if (symbol->getType().isImage()) {
5115 std::vector<spv::Decoration> memory;
5116 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5117 for (unsigned int i = 0; i < memory.size(); ++i)
5118 addDecoration(id, memory[i]);
5119 }
5120
John Kessenich140f3df2015-06-26 16:58:36 -06005121 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005122 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005123 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005124 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005125
John Kessenichecba76f2017-01-06 00:34:48 -07005126#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005127 if (builtIn == spv::BuiltInSampleMask) {
5128 spv::Decoration decoration;
5129 // GL_NV_sample_mask_override_coverage extension
5130 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005131 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005132 else
5133 decoration = (spv::Decoration)spv::DecorationMax;
5134 addDecoration(id, decoration);
5135 if (decoration != spv::DecorationMax) {
5136 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5137 }
5138 }
chaoc771d89f2017-01-13 01:10:53 -08005139 else if (builtIn == spv::BuiltInLayer) {
5140 // SPV_NV_viewport_array2 extension
5141 if (symbol->getQualifier().layoutViewportRelative)
5142 {
5143 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5144 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5145 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5146 }
5147 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5148 {
5149 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5150 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5151 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5152 }
5153 }
5154
chaoc6e5acae2016-12-20 13:28:52 -08005155 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005156 addDecoration(id, spv::DecorationPassthroughNV);
5157 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005158 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5159 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005160#endif
5161
John Kessenich140f3df2015-06-26 16:58:36 -06005162 return id;
5163}
5164
John Kessenich55e7d112015-11-15 21:33:39 -07005165// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005166void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5167{
John Kessenich4016e382016-07-15 11:53:56 -06005168 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005169 builder.addDecoration(id, dec);
5170}
5171
John Kessenich55e7d112015-11-15 21:33:39 -07005172// If 'dec' is valid, add a one-operand decoration to an object
5173void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5174{
John Kessenich4016e382016-07-15 11:53:56 -06005175 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005176 builder.addDecoration(id, dec, value);
5177}
5178
5179// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005180void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5181{
John Kessenich4016e382016-07-15 11:53:56 -06005182 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005183 builder.addMemberDecoration(id, (unsigned)member, dec);
5184}
5185
John Kessenich92187592016-02-01 13:45:25 -07005186// If 'dec' is valid, add a one-operand decoration to a struct member
5187void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5188{
John Kessenich4016e382016-07-15 11:53:56 -06005189 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005190 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5191}
5192
John Kessenich55e7d112015-11-15 21:33:39 -07005193// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005194// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005195//
5196// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5197//
5198// Recursively walk the nodes. The nodes form a tree whose leaves are
5199// regular constants, which themselves are trees that createSpvConstant()
5200// recursively walks. So, this function walks the "top" of the tree:
5201// - emit specialization constant-building instructions for specConstant
5202// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005203spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005204{
John Kessenich7cc0e282016-03-20 00:46:02 -06005205 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005206
qining4f4bb812016-04-03 23:55:17 -04005207 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005208 if (! node.getQualifier().specConstant) {
5209 // hand off to the non-spec-constant path
5210 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5211 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005212 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005213 nextConst, false);
5214 }
5215
5216 // We now know we have a specialization constant to build
5217
John Kessenichd94c0032016-05-30 19:29:40 -06005218 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005219 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5220 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5221 std::vector<spv::Id> dimConstId;
5222 for (int dim = 0; dim < 3; ++dim) {
5223 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5224 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5225 if (specConst)
5226 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5227 }
5228 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5229 }
5230
5231 // An AST node labelled as specialization constant should be a symbol node.
5232 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5233 if (auto* sn = node.getAsSymbolNode()) {
5234 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005235 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5236 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5237 // will set the builder into spec constant op instruction generating mode.
5238 sub_tree->traverse(this);
5239 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005240 } else if (auto* const_union_array = &sn->getConstArray()){
5241 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005242 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5243 builder.addName(id, sn->getName().c_str());
5244 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005245 }
5246 }
qining4f4bb812016-04-03 23:55:17 -04005247
5248 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5249 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005250 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005251 exit(1);
5252 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005253}
5254
John Kessenich140f3df2015-06-26 16:58:36 -06005255// Use 'consts' as the flattened glslang source of scalar constants to recursively
5256// build the aggregate SPIR-V constant.
5257//
5258// If there are not enough elements present in 'consts', 0 will be substituted;
5259// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5260//
qining08408382016-03-21 09:51:37 -04005261spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005262{
5263 // vector of constants for SPIR-V
5264 std::vector<spv::Id> spvConsts;
5265
5266 // Type is used for struct and array constants
5267 spv::Id typeId = convertGlslangToSpvType(glslangType);
5268
5269 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005270 glslang::TType elementType(glslangType, 0);
5271 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005272 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005273 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005274 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005275 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005276 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005277 } else if (glslangType.getStruct()) {
5278 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5279 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005280 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005281 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005282 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5283 bool zero = nextConst >= consts.size();
5284 switch (glslangType.getBasicType()) {
5285 case glslang::EbtInt:
5286 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5287 break;
5288 case glslang::EbtUint:
5289 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5290 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005291 case glslang::EbtInt64:
5292 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5293 break;
5294 case glslang::EbtUint64:
5295 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5296 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005297 case glslang::EbtFloat:
5298 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5299 break;
5300 case glslang::EbtDouble:
5301 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5302 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005303#ifdef AMD_EXTENSIONS
5304 case glslang::EbtFloat16:
5305 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5306 break;
5307#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005308 case glslang::EbtBool:
5309 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5310 break;
5311 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005312 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005313 break;
5314 }
5315 ++nextConst;
5316 }
5317 } else {
5318 // we have a non-aggregate (scalar) constant
5319 bool zero = nextConst >= consts.size();
5320 spv::Id scalar = 0;
5321 switch (glslangType.getBasicType()) {
5322 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005323 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005324 break;
5325 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005326 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005327 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005328 case glslang::EbtInt64:
5329 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5330 break;
5331 case glslang::EbtUint64:
5332 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5333 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005334 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005335 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005336 break;
5337 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005338 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005339 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005340#ifdef AMD_EXTENSIONS
5341 case glslang::EbtFloat16:
5342 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5343 break;
5344#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005345 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005346 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005347 break;
5348 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005349 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005350 break;
5351 }
5352 ++nextConst;
5353 return scalar;
5354 }
5355
5356 return builder.makeCompositeConstant(typeId, spvConsts);
5357}
5358
John Kessenich7c1aa102015-10-15 13:29:11 -06005359// Return true if the node is a constant or symbol whose reading has no
5360// non-trivial observable cost or effect.
5361bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5362{
5363 // don't know what this is
5364 if (node == nullptr)
5365 return false;
5366
5367 // a constant is safe
5368 if (node->getAsConstantUnion() != nullptr)
5369 return true;
5370
5371 // not a symbol means non-trivial
5372 if (node->getAsSymbolNode() == nullptr)
5373 return false;
5374
5375 // a symbol, depends on what's being read
5376 switch (node->getType().getQualifier().storage) {
5377 case glslang::EvqTemporary:
5378 case glslang::EvqGlobal:
5379 case glslang::EvqIn:
5380 case glslang::EvqInOut:
5381 case glslang::EvqConst:
5382 case glslang::EvqConstReadOnly:
5383 case glslang::EvqUniform:
5384 return true;
5385 default:
5386 return false;
5387 }
qining25262b32016-05-06 17:25:16 -04005388}
John Kessenich7c1aa102015-10-15 13:29:11 -06005389
5390// A node is trivial if it is a single operation with no side effects.
John Kessenich0d2b4712017-05-19 20:19:00 -06005391// Vector results seem ill-defined, currently classifying them as trivial too,
5392// to avoid scalar bool-based control-flow logic.
5393// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005394// Return true if trivial.
5395bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5396{
5397 if (node == nullptr)
5398 return false;
5399
John Kessenich0d2b4712017-05-19 20:19:00 -06005400 // count vectors as trivial
5401 if (node->getType().isVector())
5402 return true;
5403
John Kessenich7c1aa102015-10-15 13:29:11 -06005404 // symbols and constants are trivial
5405 if (isTrivialLeaf(node))
5406 return true;
5407
5408 // otherwise, it needs to be a simple operation or one or two leaf nodes
5409
5410 // not a simple operation
5411 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5412 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5413 if (binaryNode == nullptr && unaryNode == nullptr)
5414 return false;
5415
5416 // not on leaf nodes
5417 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5418 return false;
5419
5420 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5421 return false;
5422 }
5423
5424 switch (node->getAsOperator()->getOp()) {
5425 case glslang::EOpLogicalNot:
5426 case glslang::EOpConvIntToBool:
5427 case glslang::EOpConvUintToBool:
5428 case glslang::EOpConvFloatToBool:
5429 case glslang::EOpConvDoubleToBool:
5430 case glslang::EOpEqual:
5431 case glslang::EOpNotEqual:
5432 case glslang::EOpLessThan:
5433 case glslang::EOpGreaterThan:
5434 case glslang::EOpLessThanEqual:
5435 case glslang::EOpGreaterThanEqual:
5436 case glslang::EOpIndexDirect:
5437 case glslang::EOpIndexDirectStruct:
5438 case glslang::EOpLogicalXor:
5439 case glslang::EOpAny:
5440 case glslang::EOpAll:
5441 return true;
5442 default:
5443 return false;
5444 }
5445}
5446
5447// Emit short-circuiting code, where 'right' is never evaluated unless
5448// the left side is true (for &&) or false (for ||).
5449spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5450{
5451 spv::Id boolTypeId = builder.makeBoolType();
5452
5453 // emit left operand
5454 builder.clearAccessChain();
5455 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005456 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005457
5458 // Operands to accumulate OpPhi operands
5459 std::vector<spv::Id> phiOperands;
5460 // accumulate left operand's phi information
5461 phiOperands.push_back(leftId);
5462 phiOperands.push_back(builder.getBuildPoint()->getId());
5463
5464 // Make the two kinds of operation symmetric with a "!"
5465 // || => emit "if (! left) result = right"
5466 // && => emit "if ( left) result = right"
5467 //
5468 // TODO: this runtime "not" for || could be avoided by adding functionality
5469 // to 'builder' to have an "else" without an "then"
5470 if (op == glslang::EOpLogicalOr)
5471 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5472
5473 // make an "if" based on the left value
5474 spv::Builder::If ifBuilder(leftId, builder);
5475
5476 // emit right operand as the "then" part of the "if"
5477 builder.clearAccessChain();
5478 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005479 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005480
5481 // accumulate left operand's phi information
5482 phiOperands.push_back(rightId);
5483 phiOperands.push_back(builder.getBuildPoint()->getId());
5484
5485 // finish the "if"
5486 ifBuilder.makeEndIf();
5487
5488 // phi together the two results
5489 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5490}
5491
Rex Xu9d93a232016-05-05 12:30:44 +08005492// Return type Id of the imported set of extended instructions corresponds to the name.
5493// Import this set if it has not been imported yet.
5494spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5495{
5496 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5497 return extBuiltinMap[name];
5498 else {
Rex Xu51596642016-09-21 18:56:12 +08005499 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005500 spv::Id extBuiltins = builder.import(name);
5501 extBuiltinMap[name] = extBuiltins;
5502 return extBuiltins;
5503 }
5504}
5505
John Kessenich140f3df2015-06-26 16:58:36 -06005506}; // end anonymous namespace
5507
5508namespace glslang {
5509
John Kessenich68d78fd2015-07-12 19:28:10 -06005510void GetSpirvVersion(std::string& version)
5511{
John Kessenich9e55f632015-07-15 10:03:39 -06005512 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005513 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005514 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005515 version = buf;
5516}
5517
John Kessenich140f3df2015-06-26 16:58:36 -06005518// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005519void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005520{
5521 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005522 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005523 if (out.fail())
5524 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005525 for (int i = 0; i < (int)spirv.size(); ++i) {
5526 unsigned int word = spirv[i];
5527 out.write((const char*)&word, 4);
5528 }
5529 out.close();
5530}
5531
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005532// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005533void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005534{
5535 std::ofstream out;
5536 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005537 if (out.fail())
5538 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005539 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005540 if (varName != nullptr) {
5541 out << "\t #pragma once" << std::endl;
5542 out << "const uint32_t " << varName << "[] = {" << std::endl;
5543 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005544 const int WORDS_PER_LINE = 8;
5545 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5546 out << "\t";
5547 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5548 const unsigned int word = spirv[i + j];
5549 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5550 if (i + j + 1 < (int)spirv.size()) {
5551 out << ",";
5552 }
5553 }
5554 out << std::endl;
5555 }
Flavio15017db2017-02-15 14:29:33 -08005556 if (varName != nullptr) {
5557 out << "};";
5558 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005559 out.close();
5560}
5561
John Kessenich140f3df2015-06-26 16:58:36 -06005562//
5563// Set up the glslang traversal
5564//
5565void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5566{
Lei Zhang17535f72016-05-04 15:55:59 -04005567 spv::SpvBuildLogger logger;
5568 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005569}
5570
Lei Zhang17535f72016-05-04 15:55:59 -04005571void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005572{
John Kessenich140f3df2015-06-26 16:58:36 -06005573 TIntermNode* root = intermediate.getTreeRoot();
5574
5575 if (root == 0)
5576 return;
5577
5578 glslang::GetThreadPoolAllocator().push();
5579
Lei Zhang17535f72016-05-04 15:55:59 -04005580 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005581 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005582 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005583 it.dumpSpv(spirv);
5584
5585 glslang::GetThreadPoolAllocator().pop();
5586}
5587
5588}; // end namespace glslang