blob: ebb7230088ac6255b8df96b8794b2e3ebf921bec [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);
John Kessenich140f3df2015-06-26 16:58:36 -0600125 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
126 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600127 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
128 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
129 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600130 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700131 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600132 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600133 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
134 glslang::TLayoutPacking, const glslang::TQualifier&);
135 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
136 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700137 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700138 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800139 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600140 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700141 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700142 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
143 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
144 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 +0100145 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600146
John Kessenich6fccb3c2016-09-19 16:01:41 -0600147 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600148 void makeFunctions(const glslang::TIntermSequence&);
149 void makeGlobalInitializers(const glslang::TIntermSequence&);
150 void visitFunctions(const glslang::TIntermSequence&);
151 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800152 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600153 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
154 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600155 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
156
qining25262b32016-05-06 17:25:16 -0400157 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);
158 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
159 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 +0800160 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 +0800161 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 -0600162 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800163 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 +0800164 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800165 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600166 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 +0800167 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
169 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700170 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600171 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700172 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400173 spv::Id createSpvConstant(const glslang::TIntermTyped&);
174 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600175 bool isTrivialLeaf(const glslang::TIntermTyped* node);
176 bool isTrivial(const glslang::TIntermTyped* node);
177 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800178 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600179
180 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600181 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700182 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600183 int sequenceDepth;
184
Lei Zhang17535f72016-05-04 15:55:59 -0400185 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400186
John Kessenich140f3df2015-06-26 16:58:36 -0600187 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
188 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700189 bool inEntryPoint;
190 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700191 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 -0700192 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600193 const glslang::TIntermediate* glslangIntermediate;
194 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800195 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600196
John Kessenich2f273362015-07-18 22:34:27 -0600197 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600198 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600199 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700200 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600201 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 -0600202 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600203};
204
205//
206// Helper functions for translating glslang representations to SPIR-V enumerants.
207//
208
209// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700210spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600211{
John Kessenich66e2faf2016-03-12 18:34:36 -0700212 switch (source) {
213 case glslang::EShSourceGlsl:
214 switch (profile) {
215 case ENoProfile:
216 case ECoreProfile:
217 case ECompatibilityProfile:
218 return spv::SourceLanguageGLSL;
219 case EEsProfile:
220 return spv::SourceLanguageESSL;
221 default:
222 return spv::SourceLanguageUnknown;
223 }
224 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600225 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600226 default:
227 return spv::SourceLanguageUnknown;
228 }
229}
230
231// Translate glslang language (stage) to SPIR-V execution model.
232spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
233{
234 switch (stage) {
235 case EShLangVertex: return spv::ExecutionModelVertex;
236 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
237 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
238 case EShLangGeometry: return spv::ExecutionModelGeometry;
239 case EShLangFragment: return spv::ExecutionModelFragment;
240 case EShLangCompute: return spv::ExecutionModelGLCompute;
241 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700242 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600243 return spv::ExecutionModelFragment;
244 }
245}
246
247// Translate glslang type to SPIR-V storage class.
248spv::StorageClass TranslateStorageClass(const glslang::TType& type)
249{
250 if (type.getQualifier().isPipeInput())
251 return spv::StorageClassInput;
252 else if (type.getQualifier().isPipeOutput())
253 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700254 else if (type.getBasicType() == glslang::EbtAtomicUint)
255 return spv::StorageClassAtomicCounter;
John Kessenich4a57dce2017-02-24 19:15:46 -0700256 else if (type.containsOpaque())
257 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600258 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700259 if (type.getQualifier().layoutPushConstant)
260 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600261 if (type.getBasicType() == glslang::EbtBlock)
262 return spv::StorageClassUniform;
263 else
264 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 } else {
266 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700267 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
268 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600269 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
270 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400271 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700272 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600273 return spv::StorageClassFunction;
274 }
275 }
276}
277
278// Translate glslang sampler type to SPIR-V dimensionality.
279spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
280{
281 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700282 case glslang::Esd1D: return spv::Dim1D;
283 case glslang::Esd2D: return spv::Dim2D;
284 case glslang::Esd3D: return spv::Dim3D;
285 case glslang::EsdCube: return spv::DimCube;
286 case glslang::EsdRect: return spv::DimRect;
287 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700288 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600289 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700290 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600291 return spv::Dim2D;
292 }
293}
294
John Kessenichf6640762016-08-01 19:44:00 -0600295// Translate glslang precision to SPIR-V precision decorations.
296spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600297{
John Kessenichf6640762016-08-01 19:44:00 -0600298 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700299 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600300 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600301 default:
302 return spv::NoPrecision;
303 }
304}
305
John Kessenichf6640762016-08-01 19:44:00 -0600306// Translate glslang type to SPIR-V precision decorations.
307spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
308{
309 return TranslatePrecisionDecoration(type.getQualifier().precision);
310}
311
John Kessenich140f3df2015-06-26 16:58:36 -0600312// Translate glslang type to SPIR-V block decorations.
313spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
314{
315 if (type.getBasicType() == glslang::EbtBlock) {
316 switch (type.getQualifier().storage) {
317 case glslang::EvqUniform: return spv::DecorationBlock;
318 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
319 case glslang::EvqVaryingIn: return spv::DecorationBlock;
320 case glslang::EvqVaryingOut: return spv::DecorationBlock;
321 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700322 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600323 break;
324 }
325 }
326
John Kessenich4016e382016-07-15 11:53:56 -0600327 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600328}
329
Rex Xu1da878f2016-02-21 20:59:01 +0800330// Translate glslang type to SPIR-V memory decorations.
331void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
332{
333 if (qualifier.coherent)
334 memory.push_back(spv::DecorationCoherent);
335 if (qualifier.volatil)
336 memory.push_back(spv::DecorationVolatile);
337 if (qualifier.restrict)
338 memory.push_back(spv::DecorationRestrict);
339 if (qualifier.readonly)
340 memory.push_back(spv::DecorationNonWritable);
341 if (qualifier.writeonly)
342 memory.push_back(spv::DecorationNonReadable);
343}
344
John Kessenich140f3df2015-06-26 16:58:36 -0600345// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700346spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600347{
348 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700349 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600350 case glslang::ElmRowMajor:
351 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700352 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600353 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700354 default:
355 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357 }
358 } else {
359 switch (type.getBasicType()) {
360 default:
John Kessenich4016e382016-07-15 11:53:56 -0600361 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600362 break;
363 case glslang::EbtBlock:
364 switch (type.getQualifier().storage) {
365 case glslang::EvqUniform:
366 case glslang::EvqBuffer:
367 switch (type.getQualifier().layoutPacking) {
368 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600369 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
370 default:
John Kessenich4016e382016-07-15 11:53:56 -0600371 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600372 }
373 case glslang::EvqVaryingIn:
374 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700375 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600376 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600377 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700378 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600379 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600380 }
381 }
382 }
383}
384
385// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600386// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700387// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800388spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600389{
Rex Xubbceed72016-05-21 09:40:44 +0800390 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700391 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600392 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800393 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700394 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700395 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600396 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800397#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800398 else if (qualifier.explicitInterp) {
399 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800400 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800401 }
Rex Xu9d93a232016-05-05 12:30:44 +0800402#endif
Rex Xubbceed72016-05-21 09:40:44 +0800403 else
John Kessenich4016e382016-07-15 11:53:56 -0600404 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800405}
406
407// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600408// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800409// should be applied.
410spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
411{
412 if (qualifier.patch)
413 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700414 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600415 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700416 else if (qualifier.sample) {
417 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600418 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700419 } else
John Kessenich4016e382016-07-15 11:53:56 -0600420 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600421}
422
John Kessenich92187592016-02-01 13:45:25 -0700423// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700424spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600425{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700426 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600427 return spv::DecorationInvariant;
428 else
John Kessenich4016e382016-07-15 11:53:56 -0600429 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600430}
431
qining9220dbb2016-05-04 17:34:38 -0400432// If glslang type is noContraction, return SPIR-V NoContraction decoration.
433spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
434{
435 if (qualifier.noContraction)
436 return spv::DecorationNoContraction;
437 else
John Kessenich4016e382016-07-15 11:53:56 -0600438 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400439}
440
David Netoa901ffe2016-06-08 14:11:40 +0100441// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
442// associated capabilities when required. For some built-in variables, a capability
443// is generated only when using the variable in an executable instruction, but not when
444// just declaring a struct member variable with it. This is true for PointSize,
445// ClipDistance, and CullDistance.
446spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600447{
448 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700449 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600450 // Defer adding the capability until the built-in is actually used.
451 if (! memberDeclaration) {
452 switch (glslangIntermediate->getStage()) {
453 case EShLangGeometry:
454 builder.addCapability(spv::CapabilityGeometryPointSize);
455 break;
456 case EShLangTessControl:
457 case EShLangTessEvaluation:
458 builder.addCapability(spv::CapabilityTessellationPointSize);
459 break;
460 default:
461 break;
462 }
John Kessenich92187592016-02-01 13:45:25 -0700463 }
464 return spv::BuiltInPointSize;
465
John Kessenichebb50532016-05-16 19:22:05 -0600466 // These *Distance capabilities logically belong here, but if the member is declared and
467 // then never used, consumers of SPIR-V prefer the capability not be declared.
468 // They are now generated when used, rather than here when declared.
469 // Potentially, the specification should be more clear what the minimum
470 // use needed is to trigger the capability.
471 //
John Kessenich92187592016-02-01 13:45:25 -0700472 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100473 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800474 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700475 return spv::BuiltInClipDistance;
476
477 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100478 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800479 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700480 return spv::BuiltInCullDistance;
481
482 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800483 if (!memberDeclaration) {
484 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800485#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800486 if (glslangIntermediate->getStage() == EShLangVertex ||
487 glslangIntermediate->getStage() == EShLangTessControl ||
488 glslangIntermediate->getStage() == EShLangTessEvaluation) {
489
490 builder.addExtension(spv::E_SPV_NV_viewport_array2);
491 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
492 }
chaoc771d89f2017-01-13 01:10:53 -0800493#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800494 }
John Kessenich92187592016-02-01 13:45:25 -0700495 return spv::BuiltInViewportIndex;
496
John Kessenich5e801132016-02-15 11:09:46 -0700497 case glslang::EbvSampleId:
498 builder.addCapability(spv::CapabilitySampleRateShading);
499 return spv::BuiltInSampleId;
500
501 case glslang::EbvSamplePosition:
502 builder.addCapability(spv::CapabilitySampleRateShading);
503 return spv::BuiltInSamplePosition;
504
505 case glslang::EbvSampleMask:
506 builder.addCapability(spv::CapabilitySampleRateShading);
507 return spv::BuiltInSampleMask;
508
John Kessenich78a45572016-07-08 14:05:15 -0600509 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800510 if (!memberDeclaration) {
511 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800512#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800513 if (glslangIntermediate->getStage() == EShLangVertex ||
514 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800515 glslangIntermediate->getStage() == EShLangTessEvaluation) {
516
chaoc771d89f2017-01-13 01:10:53 -0800517 builder.addExtension(spv::E_SPV_NV_viewport_array2);
518 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
519 }
chaoc771d89f2017-01-13 01:10:53 -0800520#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800521 }
522
John Kessenich78a45572016-07-08 14:05:15 -0600523 return spv::BuiltInLayer;
524
John Kessenich140f3df2015-06-26 16:58:36 -0600525 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600526 case glslang::EbvVertexId: return spv::BuiltInVertexId;
527 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700528 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
529 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800530
John Kessenichda581a22015-10-14 14:10:30 -0600531 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800532 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
533 builder.addCapability(spv::CapabilityDrawParameters);
534 return spv::BuiltInBaseVertex;
535
John Kessenichda581a22015-10-14 14:10:30 -0600536 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800537 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
538 builder.addCapability(spv::CapabilityDrawParameters);
539 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200540
John Kessenichda581a22015-10-14 14:10:30 -0600541 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800542 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
543 builder.addCapability(spv::CapabilityDrawParameters);
544 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200545
546 case glslang::EbvPrimitiveId:
547 if (glslangIntermediate->getStage() == EShLangFragment)
548 builder.addCapability(spv::CapabilityGeometry);
549 return spv::BuiltInPrimitiveId;
550
John Kessenich140f3df2015-06-26 16:58:36 -0600551 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600552 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
553 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
554 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
555 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
556 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
557 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
558 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600559 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
560 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
561 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
562 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
563 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
564 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
565 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
566 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800567
Rex Xu574ab042016-04-14 16:53:07 +0800568 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800569 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800570 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
571 return spv::BuiltInSubgroupSize;
572
Rex Xu574ab042016-04-14 16:53:07 +0800573 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800574 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800575 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
576 return spv::BuiltInSubgroupLocalInvocationId;
577
Rex Xu574ab042016-04-14 16:53:07 +0800578 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800579 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
580 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
581 return spv::BuiltInSubgroupEqMaskKHR;
582
Rex Xu574ab042016-04-14 16:53:07 +0800583 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800584 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
585 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
586 return spv::BuiltInSubgroupGeMaskKHR;
587
Rex Xu574ab042016-04-14 16:53:07 +0800588 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800589 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
590 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
591 return spv::BuiltInSubgroupGtMaskKHR;
592
Rex Xu574ab042016-04-14 16:53:07 +0800593 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800594 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
595 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
596 return spv::BuiltInSubgroupLeMaskKHR;
597
Rex Xu574ab042016-04-14 16:53:07 +0800598 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800599 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
600 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
601 return spv::BuiltInSubgroupLtMaskKHR;
602
Rex Xu9d93a232016-05-05 12:30:44 +0800603#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800604 case glslang::EbvBaryCoordNoPersp:
605 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
606 return spv::BuiltInBaryCoordNoPerspAMD;
607
608 case glslang::EbvBaryCoordNoPerspCentroid:
609 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
610 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
611
612 case glslang::EbvBaryCoordNoPerspSample:
613 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
614 return spv::BuiltInBaryCoordNoPerspSampleAMD;
615
616 case glslang::EbvBaryCoordSmooth:
617 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
618 return spv::BuiltInBaryCoordSmoothAMD;
619
620 case glslang::EbvBaryCoordSmoothCentroid:
621 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
622 return spv::BuiltInBaryCoordSmoothCentroidAMD;
623
624 case glslang::EbvBaryCoordSmoothSample:
625 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
626 return spv::BuiltInBaryCoordSmoothSampleAMD;
627
628 case glslang::EbvBaryCoordPullModel:
629 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
630 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800631#endif
chaoc771d89f2017-01-13 01:10:53 -0800632
John Kessenich6c8aaac2017-02-27 01:20:51 -0700633 case glslang::EbvDeviceIndex:
634 builder.addExtension(spv::E_SPV_KHR_device_group);
635 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700636 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700637
638 case glslang::EbvViewIndex:
639 builder.addExtension(spv::E_SPV_KHR_multiview);
640 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700641 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700642
chaoc771d89f2017-01-13 01:10:53 -0800643#ifdef NV_EXTENSIONS
644 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800645 if (!memberDeclaration) {
646 builder.addExtension(spv::E_SPV_NV_viewport_array2);
647 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
648 }
chaoc771d89f2017-01-13 01:10:53 -0800649 return spv::BuiltInViewportMaskNV;
650 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800651 if (!memberDeclaration) {
652 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
653 builder.addCapability(spv::CapabilityShaderStereoViewNV);
654 }
chaoc771d89f2017-01-13 01:10:53 -0800655 return spv::BuiltInSecondaryPositionNV;
656 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800657 if (!memberDeclaration) {
658 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
659 builder.addCapability(spv::CapabilityShaderStereoViewNV);
660 }
chaoc771d89f2017-01-13 01:10:53 -0800661 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800662 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800663 if (!memberDeclaration) {
664 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
665 builder.addCapability(spv::CapabilityPerViewAttributesNV);
666 }
chaocdf3956c2017-02-14 14:52:34 -0800667 return spv::BuiltInPositionPerViewNV;
668 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800669 if (!memberDeclaration) {
670 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
671 builder.addCapability(spv::CapabilityPerViewAttributesNV);
672 }
chaocdf3956c2017-02-14 14:52:34 -0800673 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800674#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800675 default:
676 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600677 }
678}
679
Rex Xufc618912015-09-09 16:42:49 +0800680// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700681spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800682{
683 assert(type.getBasicType() == glslang::EbtSampler);
684
John Kessenich5d0fa972016-02-15 11:57:00 -0700685 // Check for capabilities
686 switch (type.getQualifier().layoutFormat) {
687 case glslang::ElfRg32f:
688 case glslang::ElfRg16f:
689 case glslang::ElfR11fG11fB10f:
690 case glslang::ElfR16f:
691 case glslang::ElfRgba16:
692 case glslang::ElfRgb10A2:
693 case glslang::ElfRg16:
694 case glslang::ElfRg8:
695 case glslang::ElfR16:
696 case glslang::ElfR8:
697 case glslang::ElfRgba16Snorm:
698 case glslang::ElfRg16Snorm:
699 case glslang::ElfRg8Snorm:
700 case glslang::ElfR16Snorm:
701 case glslang::ElfR8Snorm:
702
703 case glslang::ElfRg32i:
704 case glslang::ElfRg16i:
705 case glslang::ElfRg8i:
706 case glslang::ElfR16i:
707 case glslang::ElfR8i:
708
709 case glslang::ElfRgb10a2ui:
710 case glslang::ElfRg32ui:
711 case glslang::ElfRg16ui:
712 case glslang::ElfRg8ui:
713 case glslang::ElfR16ui:
714 case glslang::ElfR8ui:
715 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
716 break;
717
718 default:
719 break;
720 }
721
722 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800723 switch (type.getQualifier().layoutFormat) {
724 case glslang::ElfNone: return spv::ImageFormatUnknown;
725 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
726 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
727 case glslang::ElfR32f: return spv::ImageFormatR32f;
728 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
729 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
730 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
731 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
732 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
733 case glslang::ElfR16f: return spv::ImageFormatR16f;
734 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
735 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
736 case glslang::ElfRg16: return spv::ImageFormatRg16;
737 case glslang::ElfRg8: return spv::ImageFormatRg8;
738 case glslang::ElfR16: return spv::ImageFormatR16;
739 case glslang::ElfR8: return spv::ImageFormatR8;
740 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
741 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
742 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
743 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
744 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
745 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
746 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
747 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
748 case glslang::ElfR32i: return spv::ImageFormatR32i;
749 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
750 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
751 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
752 case glslang::ElfR16i: return spv::ImageFormatR16i;
753 case glslang::ElfR8i: return spv::ImageFormatR8i;
754 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
755 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
756 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
757 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
758 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
759 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
760 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
761 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
762 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
763 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600764 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800765 }
766}
767
qining25262b32016-05-06 17:25:16 -0400768// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700769// descriptor set.
770bool IsDescriptorResource(const glslang::TType& type)
771{
John Kessenichf7497e22016-03-08 21:36:22 -0700772 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700773 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700774 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700775
776 // non block...
777 // basically samplerXXX/subpass/sampler/texture are all included
778 // if they are the global-scope-class, not the function parameter
779 // (or local, if they ever exist) class.
780 if (type.getBasicType() == glslang::EbtSampler)
781 return type.getQualifier().isUniformOrBuffer();
782
783 // None of the above.
784 return false;
785}
786
John Kesseniche0b6cad2015-12-24 10:30:13 -0700787void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
788{
789 if (child.layoutMatrix == glslang::ElmNone)
790 child.layoutMatrix = parent.layoutMatrix;
791
792 if (parent.invariant)
793 child.invariant = true;
794 if (parent.nopersp)
795 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800796#ifdef AMD_EXTENSIONS
797 if (parent.explicitInterp)
798 child.explicitInterp = true;
799#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700800 if (parent.flat)
801 child.flat = true;
802 if (parent.centroid)
803 child.centroid = true;
804 if (parent.patch)
805 child.patch = true;
806 if (parent.sample)
807 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800808 if (parent.coherent)
809 child.coherent = true;
810 if (parent.volatil)
811 child.volatil = true;
812 if (parent.restrict)
813 child.restrict = true;
814 if (parent.readonly)
815 child.readonly = true;
816 if (parent.writeonly)
817 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700818}
819
John Kessenichf2b7f332016-09-01 17:05:23 -0600820bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700821{
John Kessenich7b9fa252016-01-21 18:56:57 -0700822 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600823 // - struct members might inherit from a struct declaration
824 // (note that non-block structs don't explicitly inherit,
825 // only implicitly, meaning no decoration involved)
826 // - affect decorations on the struct members
827 // (note smooth does not, and expecting something like volatile
828 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700829 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600830 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700831}
832
John Kessenich140f3df2015-06-26 16:58:36 -0600833//
834// Implement the TGlslangToSpvTraverser class.
835//
836
Lei Zhang17535f72016-05-04 15:55:59 -0400837TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600838 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
839 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400840 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700841 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600842 glslangIntermediate(glslangIntermediate)
843{
844 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
845
846 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700847 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600848 stdBuiltins = builder.import("GLSL.std.450");
849 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600850 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
851 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600852
853 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600854 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
855 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600856 builder.addSourceExtension(it->c_str());
857
858 // Add the top-level modes for this shader.
859
John Kessenich92187592016-02-01 13:45:25 -0700860 if (glslangIntermediate->getXfbMode()) {
861 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600862 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700863 }
John Kessenich140f3df2015-06-26 16:58:36 -0600864
865 unsigned int mode;
866 switch (glslangIntermediate->getStage()) {
867 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600868 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600869 break;
870
steve-lunarge7412492017-03-23 11:56:07 -0600871 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600872 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600873 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600874
steve-lunarge7412492017-03-23 11:56:07 -0600875 glslang::TLayoutGeometry primitive;
876
877 if (glslangIntermediate->getStage() == EShLangTessControl) {
878 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
879 primitive = glslangIntermediate->getOutputPrimitive();
880 } else {
881 primitive = glslangIntermediate->getInputPrimitive();
882 }
883
884 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700885 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
886 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
887 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600888 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600889 }
John Kessenich4016e382016-07-15 11:53:56 -0600890 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600891 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
892
John Kesseniche6903322015-10-13 16:29:02 -0600893 switch (glslangIntermediate->getVertexSpacing()) {
894 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
895 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
896 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600897 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600898 }
John Kessenich4016e382016-07-15 11:53:56 -0600899 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600900 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
901
902 switch (glslangIntermediate->getVertexOrder()) {
903 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
904 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600905 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600906 }
John Kessenich4016e382016-07-15 11:53:56 -0600907 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600908 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
909
910 if (glslangIntermediate->getPointMode())
911 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600912 break;
913
914 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600915 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600916 switch (glslangIntermediate->getInputPrimitive()) {
917 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
918 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
919 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700920 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600921 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600922 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600923 }
John Kessenich4016e382016-07-15 11:53:56 -0600924 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600925 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600926
John Kessenich140f3df2015-06-26 16:58:36 -0600927 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
928
929 switch (glslangIntermediate->getOutputPrimitive()) {
930 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
931 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
932 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600933 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600934 }
John Kessenich4016e382016-07-15 11:53:56 -0600935 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600936 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
937 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
938 break;
939
940 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600941 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600942 if (glslangIntermediate->getPixelCenterInteger())
943 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600944
John Kessenich140f3df2015-06-26 16:58:36 -0600945 if (glslangIntermediate->getOriginUpperLeft())
946 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600947 else
948 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600949
950 if (glslangIntermediate->getEarlyFragmentTests())
951 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
952
953 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600954 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
955 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600956 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600957 }
John Kessenich4016e382016-07-15 11:53:56 -0600958 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600959 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
960
961 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
962 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600963 break;
964
965 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600966 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600967 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
968 glslangIntermediate->getLocalSize(1),
969 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600970 break;
971
972 default:
973 break;
974 }
John Kessenich140f3df2015-06-26 16:58:36 -0600975}
976
John Kessenichfca82622016-11-26 13:23:20 -0700977// Finish creating SPV, after the traversal is complete.
978void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700979{
John Kessenich517fe7a2016-11-26 13:31:47 -0700980 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700981 builder.setBuildPoint(shaderEntry->getLastBlock());
982 builder.leaveFunction();
983 }
984
John Kessenich7ba63412015-12-20 17:37:07 -0700985 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100986 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
987 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700988
qiningda397332016-03-09 19:54:03 -0500989 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700990}
991
John Kessenichfca82622016-11-26 13:23:20 -0700992// Write the SPV into 'out'.
993void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600994{
John Kessenichfca82622016-11-26 13:23:20 -0700995 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600996}
997
998//
999// Implement the traversal functions.
1000//
1001// Return true from interior nodes to have the external traversal
1002// continue on to children. Return false if children were
1003// already processed.
1004//
1005
1006//
qining25262b32016-05-06 17:25:16 -04001007// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001008// - uniform/input reads
1009// - output writes
1010// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1011// - something simple that degenerates into the last bullet
1012//
1013void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1014{
qining75d1d802016-04-06 14:42:01 -04001015 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1016 if (symbol->getType().getQualifier().isSpecConstant())
1017 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1018
John Kessenich140f3df2015-06-26 16:58:36 -06001019 // getSymbolId() will set up all the IO decorations on the first call.
1020 // Formal function parameters were mapped during makeFunctions().
1021 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001022
1023 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1024 if (builder.isPointer(id)) {
1025 spv::StorageClass sc = builder.getStorageClass(id);
1026 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1027 iOSet.insert(id);
1028 }
1029
1030 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001031 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001032 // Prepare to generate code for the access
1033
1034 // L-value chains will be computed left to right. We're on the symbol now,
1035 // which is the left-most part of the access chain, so now is "clear" time,
1036 // followed by setting the base.
1037 builder.clearAccessChain();
1038
1039 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001040 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001041 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001042 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001043 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001044 // These are also pure R-values.
1045 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001046 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001047 builder.setAccessChainRValue(id);
1048 else
1049 builder.setAccessChainLValue(id);
1050 }
1051}
1052
1053bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1054{
qining40887662016-04-03 22:20:42 -04001055 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1056 if (node->getType().getQualifier().isSpecConstant())
1057 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1058
John Kessenich140f3df2015-06-26 16:58:36 -06001059 // First, handle special cases
1060 switch (node->getOp()) {
1061 case glslang::EOpAssign:
1062 case glslang::EOpAddAssign:
1063 case glslang::EOpSubAssign:
1064 case glslang::EOpMulAssign:
1065 case glslang::EOpVectorTimesMatrixAssign:
1066 case glslang::EOpVectorTimesScalarAssign:
1067 case glslang::EOpMatrixTimesScalarAssign:
1068 case glslang::EOpMatrixTimesMatrixAssign:
1069 case glslang::EOpDivAssign:
1070 case glslang::EOpModAssign:
1071 case glslang::EOpAndAssign:
1072 case glslang::EOpInclusiveOrAssign:
1073 case glslang::EOpExclusiveOrAssign:
1074 case glslang::EOpLeftShiftAssign:
1075 case glslang::EOpRightShiftAssign:
1076 // A bin-op assign "a += b" means the same thing as "a = a + b"
1077 // where a is evaluated before b. For a simple assignment, GLSL
1078 // says to evaluate the left before the right. So, always, left
1079 // node then right node.
1080 {
1081 // get the left l-value, save it away
1082 builder.clearAccessChain();
1083 node->getLeft()->traverse(this);
1084 spv::Builder::AccessChain lValue = builder.getAccessChain();
1085
1086 // evaluate the right
1087 builder.clearAccessChain();
1088 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001089 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001090
1091 if (node->getOp() != glslang::EOpAssign) {
1092 // the left is also an r-value
1093 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001094 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001095
1096 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001097 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001098 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001099 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1100 node->getType().getBasicType());
1101
1102 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001103 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001104 }
1105
1106 // store the result
1107 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001108 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001109
1110 // assignments are expressions having an rValue after they are evaluated...
1111 builder.clearAccessChain();
1112 builder.setAccessChainRValue(rValue);
1113 }
1114 return false;
1115 case glslang::EOpIndexDirect:
1116 case glslang::EOpIndexDirectStruct:
1117 {
1118 // Get the left part of the access chain.
1119 node->getLeft()->traverse(this);
1120
1121 // Add the next element in the chain
1122
David Netoa901ffe2016-06-08 14:11:40 +01001123 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001124 if (! node->getLeft()->getType().isArray() &&
1125 node->getLeft()->getType().isVector() &&
1126 node->getOp() == glslang::EOpIndexDirect) {
1127 // This is essentially a hard-coded vector swizzle of size 1,
1128 // so short circuit the access-chain stuff with a swizzle.
1129 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001130 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001131 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001132 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001133 int spvIndex = glslangIndex;
1134 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1135 node->getOp() == glslang::EOpIndexDirectStruct)
1136 {
1137 // This may be, e.g., an anonymous block-member selection, which generally need
1138 // index remapping due to hidden members in anonymous blocks.
1139 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1140 assert(remapper.size() > 0);
1141 spvIndex = remapper[glslangIndex];
1142 }
John Kessenichebb50532016-05-16 19:22:05 -06001143
David Netoa901ffe2016-06-08 14:11:40 +01001144 // normal case for indexing array or structure or block
1145 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1146
1147 // Add capabilities here for accessing PointSize and clip/cull distance.
1148 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001149 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001150 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001151 }
1152 }
1153 return false;
1154 case glslang::EOpIndexIndirect:
1155 {
1156 // Structure or array or vector indirection.
1157 // Will use native SPIR-V access-chain for struct and array indirection;
1158 // matrices are arrays of vectors, so will also work for a matrix.
1159 // Will use the access chain's 'component' for variable index into a vector.
1160
1161 // This adapter is building access chains left to right.
1162 // Set up the access chain to the left.
1163 node->getLeft()->traverse(this);
1164
1165 // save it so that computing the right side doesn't trash it
1166 spv::Builder::AccessChain partial = builder.getAccessChain();
1167
1168 // compute the next index in the chain
1169 builder.clearAccessChain();
1170 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001171 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001172
1173 // restore the saved access chain
1174 builder.setAccessChain(partial);
1175
1176 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001177 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001178 else
John Kessenichfa668da2015-09-13 14:46:30 -06001179 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001180 }
1181 return false;
1182 case glslang::EOpVectorSwizzle:
1183 {
1184 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001185 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001186 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001187 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001188 }
1189 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001190 case glslang::EOpMatrixSwizzle:
1191 logger->missingFunctionality("matrix swizzle");
1192 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001193 case glslang::EOpLogicalOr:
1194 case glslang::EOpLogicalAnd:
1195 {
1196
1197 // These may require short circuiting, but can sometimes be done as straight
1198 // binary operations. The right operand must be short circuited if it has
1199 // side effects, and should probably be if it is complex.
1200 if (isTrivial(node->getRight()->getAsTyped()))
1201 break; // handle below as a normal binary operation
1202 // otherwise, we need to do dynamic short circuiting on the right operand
1203 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1204 builder.clearAccessChain();
1205 builder.setAccessChainRValue(result);
1206 }
1207 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001208 default:
1209 break;
1210 }
1211
1212 // Assume generic binary op...
1213
John Kessenich32cfd492016-02-02 12:37:46 -07001214 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001215 builder.clearAccessChain();
1216 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001217 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001218
John Kessenich32cfd492016-02-02 12:37:46 -07001219 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001220 builder.clearAccessChain();
1221 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001222 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001223
John Kessenich32cfd492016-02-02 12:37:46 -07001224 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001225 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001226 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001227 convertGlslangToSpvType(node->getType()), left, right,
1228 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001229
John Kessenich50e57562015-12-21 21:21:11 -07001230 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001231 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001232 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001233 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001234 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001235 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001236 return false;
1237 }
John Kessenich140f3df2015-06-26 16:58:36 -06001238}
1239
1240bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1241{
qining40887662016-04-03 22:20:42 -04001242 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1243 if (node->getType().getQualifier().isSpecConstant())
1244 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1245
John Kessenichfc51d282015-08-19 13:34:18 -06001246 spv::Id result = spv::NoResult;
1247
1248 // try texturing first
1249 result = createImageTextureFunctionCall(node);
1250 if (result != spv::NoResult) {
1251 builder.clearAccessChain();
1252 builder.setAccessChainRValue(result);
1253
1254 return false; // done with this node
1255 }
1256
1257 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001258
1259 if (node->getOp() == glslang::EOpArrayLength) {
1260 // Quite special; won't want to evaluate the operand.
1261
1262 // Normal .length() would have been constant folded by the front-end.
1263 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001264 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001265 assert(node->getOperand()->getType().isRuntimeSizedArray());
1266 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1267 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001268 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1269 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001270
1271 builder.clearAccessChain();
1272 builder.setAccessChainRValue(length);
1273
1274 return false;
1275 }
1276
John Kessenichfc51d282015-08-19 13:34:18 -06001277 // Start by evaluating the operand
1278
John Kessenich8c8505c2016-07-26 12:50:38 -06001279 // Does it need a swizzle inversion? If so, evaluation is inverted;
1280 // operate first on the swizzle base, then apply the swizzle.
1281 spv::Id invertedType = spv::NoType;
1282 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1283 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1284 invertedType = getInvertedSwizzleType(*node->getOperand());
1285
John Kessenich140f3df2015-06-26 16:58:36 -06001286 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001287 if (invertedType != spv::NoType)
1288 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1289 else
1290 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001291
Rex Xufc618912015-09-09 16:42:49 +08001292 spv::Id operand = spv::NoResult;
1293
1294 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1295 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001296 node->getOp() == glslang::EOpAtomicCounter ||
1297 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001298 operand = builder.accessChainGetLValue(); // Special case l-value operands
1299 else
John Kessenich32cfd492016-02-02 12:37:46 -07001300 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001301
John Kessenichf6640762016-08-01 19:44:00 -06001302 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001303 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001304
1305 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001306 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001307 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001308
1309 // if not, then possibly an operation
1310 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001311 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001312
1313 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001314 if (invertedType)
1315 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1316
John Kessenich140f3df2015-06-26 16:58:36 -06001317 builder.clearAccessChain();
1318 builder.setAccessChainRValue(result);
1319
1320 return false; // done with this node
1321 }
1322
1323 // it must be a special case, check...
1324 switch (node->getOp()) {
1325 case glslang::EOpPostIncrement:
1326 case glslang::EOpPostDecrement:
1327 case glslang::EOpPreIncrement:
1328 case glslang::EOpPreDecrement:
1329 {
1330 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001331 spv::Id one = 0;
1332 if (node->getBasicType() == glslang::EbtFloat)
1333 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001334 else if (node->getBasicType() == glslang::EbtDouble)
1335 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001336#ifdef AMD_EXTENSIONS
1337 else if (node->getBasicType() == glslang::EbtFloat16)
1338 one = builder.makeFloat16Constant(1.0F);
1339#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001340 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1341 one = builder.makeInt64Constant(1);
1342 else
1343 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001344 glslang::TOperator op;
1345 if (node->getOp() == glslang::EOpPreIncrement ||
1346 node->getOp() == glslang::EOpPostIncrement)
1347 op = glslang::EOpAdd;
1348 else
1349 op = glslang::EOpSub;
1350
John Kessenichf6640762016-08-01 19:44:00 -06001351 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001352 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001353 convertGlslangToSpvType(node->getType()), operand, one,
1354 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001355 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001356
1357 // The result of operation is always stored, but conditionally the
1358 // consumed result. The consumed result is always an r-value.
1359 builder.accessChainStore(result);
1360 builder.clearAccessChain();
1361 if (node->getOp() == glslang::EOpPreIncrement ||
1362 node->getOp() == glslang::EOpPreDecrement)
1363 builder.setAccessChainRValue(result);
1364 else
1365 builder.setAccessChainRValue(operand);
1366 }
1367
1368 return false;
1369
1370 case glslang::EOpEmitStreamVertex:
1371 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1372 return false;
1373 case glslang::EOpEndStreamPrimitive:
1374 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1375 return false;
1376
1377 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001378 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001379 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001380 }
John Kessenich140f3df2015-06-26 16:58:36 -06001381}
1382
1383bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1384{
qining27e04a02016-04-14 16:40:20 -04001385 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1386 if (node->getType().getQualifier().isSpecConstant())
1387 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1388
John Kessenichfc51d282015-08-19 13:34:18 -06001389 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001390 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1391 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001392
1393 // try texturing
1394 result = createImageTextureFunctionCall(node);
1395 if (result != spv::NoResult) {
1396 builder.clearAccessChain();
1397 builder.setAccessChainRValue(result);
1398
1399 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001400 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001401 // "imageStore" is a special case, which has no result
1402 return false;
1403 }
John Kessenichfc51d282015-08-19 13:34:18 -06001404
John Kessenich140f3df2015-06-26 16:58:36 -06001405 glslang::TOperator binOp = glslang::EOpNull;
1406 bool reduceComparison = true;
1407 bool isMatrix = false;
1408 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001409 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001410
1411 assert(node->getOp());
1412
John Kessenichf6640762016-08-01 19:44:00 -06001413 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001414
1415 switch (node->getOp()) {
1416 case glslang::EOpSequence:
1417 {
1418 if (preVisit)
1419 ++sequenceDepth;
1420 else
1421 --sequenceDepth;
1422
1423 if (sequenceDepth == 1) {
1424 // If this is the parent node of all the functions, we want to see them
1425 // early, so all call points have actual SPIR-V functions to reference.
1426 // In all cases, still let the traverser visit the children for us.
1427 makeFunctions(node->getAsAggregate()->getSequence());
1428
John Kessenich6fccb3c2016-09-19 16:01:41 -06001429 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001430 // anything else gets there, so visit out of order, doing them all now.
1431 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1432
John Kessenich6a60c2f2016-12-08 21:01:59 -07001433 // 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 -06001434 // so do them manually.
1435 visitFunctions(node->getAsAggregate()->getSequence());
1436
1437 return false;
1438 }
1439
1440 return true;
1441 }
1442 case glslang::EOpLinkerObjects:
1443 {
1444 if (visit == glslang::EvPreVisit)
1445 linkageOnly = true;
1446 else
1447 linkageOnly = false;
1448
1449 return true;
1450 }
1451 case glslang::EOpComma:
1452 {
1453 // processing from left to right naturally leaves the right-most
1454 // lying around in the access chain
1455 glslang::TIntermSequence& glslangOperands = node->getSequence();
1456 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1457 glslangOperands[i]->traverse(this);
1458
1459 return false;
1460 }
1461 case glslang::EOpFunction:
1462 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001463 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001464 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001465 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001466 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001467 } else {
1468 handleFunctionEntry(node);
1469 }
1470 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001471 if (inEntryPoint)
1472 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001473 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001474 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001475 }
1476
1477 return true;
1478 case glslang::EOpParameters:
1479 // Parameters will have been consumed by EOpFunction processing, but not
1480 // the body, so we still visited the function node's children, making this
1481 // child redundant.
1482 return false;
1483 case glslang::EOpFunctionCall:
1484 {
1485 if (node->isUserDefined())
1486 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001487 // 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 -07001488 if (result) {
1489 builder.clearAccessChain();
1490 builder.setAccessChainRValue(result);
1491 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001492 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001493
1494 return false;
1495 }
1496 case glslang::EOpConstructMat2x2:
1497 case glslang::EOpConstructMat2x3:
1498 case glslang::EOpConstructMat2x4:
1499 case glslang::EOpConstructMat3x2:
1500 case glslang::EOpConstructMat3x3:
1501 case glslang::EOpConstructMat3x4:
1502 case glslang::EOpConstructMat4x2:
1503 case glslang::EOpConstructMat4x3:
1504 case glslang::EOpConstructMat4x4:
1505 case glslang::EOpConstructDMat2x2:
1506 case glslang::EOpConstructDMat2x3:
1507 case glslang::EOpConstructDMat2x4:
1508 case glslang::EOpConstructDMat3x2:
1509 case glslang::EOpConstructDMat3x3:
1510 case glslang::EOpConstructDMat3x4:
1511 case glslang::EOpConstructDMat4x2:
1512 case glslang::EOpConstructDMat4x3:
1513 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001514#ifdef AMD_EXTENSIONS
1515 case glslang::EOpConstructF16Mat2x2:
1516 case glslang::EOpConstructF16Mat2x3:
1517 case glslang::EOpConstructF16Mat2x4:
1518 case glslang::EOpConstructF16Mat3x2:
1519 case glslang::EOpConstructF16Mat3x3:
1520 case glslang::EOpConstructF16Mat3x4:
1521 case glslang::EOpConstructF16Mat4x2:
1522 case glslang::EOpConstructF16Mat4x3:
1523 case glslang::EOpConstructF16Mat4x4:
1524#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001525 isMatrix = true;
1526 // fall through
1527 case glslang::EOpConstructFloat:
1528 case glslang::EOpConstructVec2:
1529 case glslang::EOpConstructVec3:
1530 case glslang::EOpConstructVec4:
1531 case glslang::EOpConstructDouble:
1532 case glslang::EOpConstructDVec2:
1533 case glslang::EOpConstructDVec3:
1534 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001535#ifdef AMD_EXTENSIONS
1536 case glslang::EOpConstructFloat16:
1537 case glslang::EOpConstructF16Vec2:
1538 case glslang::EOpConstructF16Vec3:
1539 case glslang::EOpConstructF16Vec4:
1540#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001541 case glslang::EOpConstructBool:
1542 case glslang::EOpConstructBVec2:
1543 case glslang::EOpConstructBVec3:
1544 case glslang::EOpConstructBVec4:
1545 case glslang::EOpConstructInt:
1546 case glslang::EOpConstructIVec2:
1547 case glslang::EOpConstructIVec3:
1548 case glslang::EOpConstructIVec4:
1549 case glslang::EOpConstructUint:
1550 case glslang::EOpConstructUVec2:
1551 case glslang::EOpConstructUVec3:
1552 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001553 case glslang::EOpConstructInt64:
1554 case glslang::EOpConstructI64Vec2:
1555 case glslang::EOpConstructI64Vec3:
1556 case glslang::EOpConstructI64Vec4:
1557 case glslang::EOpConstructUint64:
1558 case glslang::EOpConstructU64Vec2:
1559 case glslang::EOpConstructU64Vec3:
1560 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001561 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001562 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001563 {
1564 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001565 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001566 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001567 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001568 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001569 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001570 std::vector<spv::Id> constituents;
1571 for (int c = 0; c < (int)arguments.size(); ++c)
1572 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001573 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001574 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001575 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001576 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001577 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001578
1579 builder.clearAccessChain();
1580 builder.setAccessChainRValue(constructed);
1581
1582 return false;
1583 }
1584
1585 // These six are component-wise compares with component-wise results.
1586 // Forward on to createBinaryOperation(), requesting a vector result.
1587 case glslang::EOpLessThan:
1588 case glslang::EOpGreaterThan:
1589 case glslang::EOpLessThanEqual:
1590 case glslang::EOpGreaterThanEqual:
1591 case glslang::EOpVectorEqual:
1592 case glslang::EOpVectorNotEqual:
1593 {
1594 // Map the operation to a binary
1595 binOp = node->getOp();
1596 reduceComparison = false;
1597 switch (node->getOp()) {
1598 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1599 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1600 default: binOp = node->getOp(); break;
1601 }
1602
1603 break;
1604 }
1605 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001606 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001607 binOp = glslang::EOpMul;
1608 break;
1609 case glslang::EOpOuterProduct:
1610 // two vectors multiplied to make a matrix
1611 binOp = glslang::EOpOuterProduct;
1612 break;
1613 case glslang::EOpDot:
1614 {
qining25262b32016-05-06 17:25:16 -04001615 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001616 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001617 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001618 binOp = glslang::EOpMul;
1619 break;
1620 }
1621 case glslang::EOpMod:
1622 // when an aggregate, this is the floating-point mod built-in function,
1623 // which can be emitted by the one in createBinaryOperation()
1624 binOp = glslang::EOpMod;
1625 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001626 case glslang::EOpEmitVertex:
1627 case glslang::EOpEndPrimitive:
1628 case glslang::EOpBarrier:
1629 case glslang::EOpMemoryBarrier:
1630 case glslang::EOpMemoryBarrierAtomicCounter:
1631 case glslang::EOpMemoryBarrierBuffer:
1632 case glslang::EOpMemoryBarrierImage:
1633 case glslang::EOpMemoryBarrierShared:
1634 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001635 case glslang::EOpAllMemoryBarrierWithGroupSync:
1636 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1637 case glslang::EOpWorkgroupMemoryBarrier:
1638 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001639 noReturnValue = true;
1640 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1641 break;
1642
John Kessenich426394d2015-07-23 10:22:48 -06001643 case glslang::EOpAtomicAdd:
1644 case glslang::EOpAtomicMin:
1645 case glslang::EOpAtomicMax:
1646 case glslang::EOpAtomicAnd:
1647 case glslang::EOpAtomicOr:
1648 case glslang::EOpAtomicXor:
1649 case glslang::EOpAtomicExchange:
1650 case glslang::EOpAtomicCompSwap:
1651 atomic = true;
1652 break;
1653
John Kessenich140f3df2015-06-26 16:58:36 -06001654 default:
1655 break;
1656 }
1657
1658 //
1659 // See if it maps to a regular operation.
1660 //
John Kessenich140f3df2015-06-26 16:58:36 -06001661 if (binOp != glslang::EOpNull) {
1662 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1663 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1664 assert(left && right);
1665
1666 builder.clearAccessChain();
1667 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001668 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001669
1670 builder.clearAccessChain();
1671 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001672 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001673
qining25262b32016-05-06 17:25:16 -04001674 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001675 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001676 left->getType().getBasicType(), reduceComparison);
1677
1678 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001679 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001680 builder.clearAccessChain();
1681 builder.setAccessChainRValue(result);
1682
1683 return false;
1684 }
1685
John Kessenich426394d2015-07-23 10:22:48 -06001686 //
1687 // Create the list of operands.
1688 //
John Kessenich140f3df2015-06-26 16:58:36 -06001689 glslang::TIntermSequence& glslangOperands = node->getSequence();
1690 std::vector<spv::Id> operands;
1691 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001692 // special case l-value operands; there are just a few
1693 bool lvalue = false;
1694 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001695 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001696 case glslang::EOpModf:
1697 if (arg == 1)
1698 lvalue = true;
1699 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001700 case glslang::EOpInterpolateAtSample:
1701 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001702#ifdef AMD_EXTENSIONS
1703 case glslang::EOpInterpolateAtVertex:
1704#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001705 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001706 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001707
1708 // Does it need a swizzle inversion? If so, evaluation is inverted;
1709 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001710 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001711 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1712 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1713 }
Rex Xu7a26c172015-12-08 17:12:09 +08001714 break;
Rex Xud4782c12015-09-06 16:30:11 +08001715 case glslang::EOpAtomicAdd:
1716 case glslang::EOpAtomicMin:
1717 case glslang::EOpAtomicMax:
1718 case glslang::EOpAtomicAnd:
1719 case glslang::EOpAtomicOr:
1720 case glslang::EOpAtomicXor:
1721 case glslang::EOpAtomicExchange:
1722 case glslang::EOpAtomicCompSwap:
1723 if (arg == 0)
1724 lvalue = true;
1725 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001726 case glslang::EOpAddCarry:
1727 case glslang::EOpSubBorrow:
1728 if (arg == 2)
1729 lvalue = true;
1730 break;
1731 case glslang::EOpUMulExtended:
1732 case glslang::EOpIMulExtended:
1733 if (arg >= 2)
1734 lvalue = true;
1735 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001736 default:
1737 break;
1738 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001739 builder.clearAccessChain();
1740 if (invertedType != spv::NoType && arg == 0)
1741 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1742 else
1743 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001744 if (lvalue)
1745 operands.push_back(builder.accessChainGetLValue());
1746 else
John Kessenich32cfd492016-02-02 12:37:46 -07001747 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001748 }
John Kessenich426394d2015-07-23 10:22:48 -06001749
1750 if (atomic) {
1751 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001752 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001753 } else {
1754 // Pass through to generic operations.
1755 switch (glslangOperands.size()) {
1756 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001757 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001758 break;
1759 case 1:
qining25262b32016-05-06 17:25:16 -04001760 result = createUnaryOperation(
1761 node->getOp(), precision,
1762 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001763 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001764 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001765 break;
1766 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001767 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001768 break;
1769 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001770 if (invertedType)
1771 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001772 }
1773
1774 if (noReturnValue)
1775 return false;
1776
1777 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001778 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001779 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001780 } else {
1781 builder.clearAccessChain();
1782 builder.setAccessChainRValue(result);
1783 return false;
1784 }
1785}
1786
John Kessenich433e9ff2017-01-26 20:31:11 -07001787// This path handles both if-then-else and ?:
1788// The if-then-else has a node type of void, while
1789// ?: has either a void or a non-void node type
1790//
1791// Leaving the result, when not void:
1792// GLSL only has r-values as the result of a :?, but
1793// if we have an l-value, that can be more efficient if it will
1794// become the base of a complex r-value expression, because the
1795// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001796bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1797{
John Kessenich433e9ff2017-01-26 20:31:11 -07001798 // See if it simple and safe to generate OpSelect instead of using control flow.
1799 // Crucially, side effects must be avoided, and there are performance trade-offs.
1800 // Return true if good idea (and safe) for OpSelect, false otherwise.
1801 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001802 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1803 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001804 return false;
1805
1806 if (node->getTrueBlock() == nullptr ||
1807 node->getFalseBlock() == nullptr)
1808 return false;
1809
1810 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1811 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1812
1813 // return true if a single operand to ? : is okay for OpSelect
1814 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001815 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001816 };
1817
1818 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1819 operandOkay(node->getFalseBlock()->getAsTyped());
1820 };
1821
1822 // Emit OpSelect for this selection.
1823 const auto handleAsOpSelect = [&]() {
1824 node->getCondition()->traverse(this);
1825 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1826 node->getTrueBlock()->traverse(this);
1827 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1828 node->getFalseBlock()->traverse(this);
1829 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1830
John Kesseniche434ad92017-03-30 10:09:28 -06001831 // smear condition to vector, if necessary (AST is always scalar)
1832 if (builder.isVector(trueValue))
1833 condition = builder.smearScalar(spv::NoPrecision, condition,
1834 builder.makeVectorType(builder.makeBoolType(),
1835 builder.getNumComponents(trueValue)));
1836
1837 spv::Id select = builder.createTriOp(spv::OpSelect,
1838 convertGlslangToSpvType(node->getType()), condition,
1839 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001840 builder.clearAccessChain();
1841 builder.setAccessChainRValue(select);
1842 };
1843
1844 // Try for OpSelect
1845
1846 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001847 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1848 if (node->getType().getQualifier().isSpecConstant())
1849 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1850
John Kessenich433e9ff2017-01-26 20:31:11 -07001851 handleAsOpSelect();
1852 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001853 }
1854
John Kessenich433e9ff2017-01-26 20:31:11 -07001855 // Instead, emit control flow...
1856
1857 // Don't handle results as temporaries, because there will be two names
1858 // and better to leave SSA to later passes.
1859 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1860 ? spv::NoResult
1861 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1862
John Kessenich140f3df2015-06-26 16:58:36 -06001863 // emit the condition before doing anything with selection
1864 node->getCondition()->traverse(this);
1865
1866 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001867 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001868
John Kessenich433e9ff2017-01-26 20:31:11 -07001869 // emit the "then" statement
1870 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001871 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001872 if (result != spv::NoResult)
1873 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001874 }
1875
John Kessenich433e9ff2017-01-26 20:31:11 -07001876 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001877 ifBuilder.makeBeginElse();
1878 // emit the "else" statement
1879 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001880 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001881 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001882 }
1883
John Kessenich433e9ff2017-01-26 20:31:11 -07001884 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001885 ifBuilder.makeEndIf();
1886
John Kessenich433e9ff2017-01-26 20:31:11 -07001887 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001888 // GLSL only has r-values as the result of a :?, but
1889 // if we have an l-value, that can be more efficient if it will
1890 // become the base of a complex r-value expression, because the
1891 // next layer copies r-values into memory to use the access-chain mechanism
1892 builder.clearAccessChain();
1893 builder.setAccessChainLValue(result);
1894 }
1895
1896 return false;
1897}
1898
1899bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1900{
1901 // emit and get the condition before doing anything with switch
1902 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001903 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001904
1905 // browse the children to sort out code segments
1906 int defaultSegment = -1;
1907 std::vector<TIntermNode*> codeSegments;
1908 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1909 std::vector<int> caseValues;
1910 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1911 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1912 TIntermNode* child = *c;
1913 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001914 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001915 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001916 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001917 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1918 } else
1919 codeSegments.push_back(child);
1920 }
1921
qining25262b32016-05-06 17:25:16 -04001922 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001923 // statements between the last case and the end of the switch statement
1924 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1925 (int)codeSegments.size() == defaultSegment)
1926 codeSegments.push_back(nullptr);
1927
1928 // make the switch statement
1929 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001930 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001931
1932 // emit all the code in the segments
1933 breakForLoop.push(false);
1934 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1935 builder.nextSwitchSegment(segmentBlocks, s);
1936 if (codeSegments[s])
1937 codeSegments[s]->traverse(this);
1938 else
1939 builder.addSwitchBreak();
1940 }
1941 breakForLoop.pop();
1942
1943 builder.endSwitch(segmentBlocks);
1944
1945 return false;
1946}
1947
1948void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1949{
1950 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001951 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001952
1953 builder.clearAccessChain();
1954 builder.setAccessChainRValue(constant);
1955}
1956
1957bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1958{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001959 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001960 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001961 // Spec requires back edges to target header blocks, and every header block
1962 // must dominate its merge block. Make a header block first to ensure these
1963 // conditions are met. By definition, it will contain OpLoopMerge, followed
1964 // by a block-ending branch. But we don't want to put any other body/test
1965 // instructions in it, since the body/test may have arbitrary instructions,
1966 // including merges of its own.
1967 builder.setBuildPoint(&blocks.head);
1968 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001969 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001970 spv::Block& test = builder.makeNewBlock();
1971 builder.createBranch(&test);
1972
1973 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001974 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001975 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001976 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001977 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1978
1979 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001980 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001981 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001982 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001983 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001984 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001985
1986 builder.setBuildPoint(&blocks.continue_target);
1987 if (node->getTerminal())
1988 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001989 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001990 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001991 builder.createBranch(&blocks.body);
1992
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001993 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001994 builder.setBuildPoint(&blocks.body);
1995 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001996 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001997 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001998 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001999
2000 builder.setBuildPoint(&blocks.continue_target);
2001 if (node->getTerminal())
2002 node->getTerminal()->traverse(this);
2003 if (node->getTest()) {
2004 node->getTest()->traverse(this);
2005 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002006 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002007 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002008 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002009 // TODO: unless there was a break/return/discard instruction
2010 // somewhere in the body, this is an infinite loop, so we should
2011 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002012 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002013 }
John Kessenich140f3df2015-06-26 16:58:36 -06002014 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002015 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002016 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002017 return false;
2018}
2019
2020bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2021{
2022 if (node->getExpression())
2023 node->getExpression()->traverse(this);
2024
2025 switch (node->getFlowOp()) {
2026 case glslang::EOpKill:
2027 builder.makeDiscard();
2028 break;
2029 case glslang::EOpBreak:
2030 if (breakForLoop.top())
2031 builder.createLoopExit();
2032 else
2033 builder.addSwitchBreak();
2034 break;
2035 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002036 builder.createLoopContinue();
2037 break;
2038 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002039 if (node->getExpression()) {
2040 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2041 spv::Id returnId = accessChainLoad(glslangReturnType);
2042 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2043 builder.clearAccessChain();
2044 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2045 builder.setAccessChainLValue(copyId);
2046 multiTypeStore(glslangReturnType, returnId);
2047 returnId = builder.createLoad(copyId);
2048 }
2049 builder.makeReturn(false, returnId);
2050 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002051 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002052
2053 builder.clearAccessChain();
2054 break;
2055
2056 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002057 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002058 break;
2059 }
2060
2061 return false;
2062}
2063
2064spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2065{
qining25262b32016-05-06 17:25:16 -04002066 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002067 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002068 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002069 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002070 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002071 }
2072
2073 // Now, handle actual variables
2074 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
2075 spv::Id spvType = convertGlslangToSpvType(node->getType());
2076
2077 const char* name = node->getName().c_str();
2078 if (glslang::IsAnonymous(name))
2079 name = "";
2080
2081 return builder.createVariable(storageClass, spvType, name);
2082}
2083
2084// Return type Id of the sampled type.
2085spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2086{
2087 switch (sampler.type) {
2088 case glslang::EbtFloat: return builder.makeFloatType(32);
2089 case glslang::EbtInt: return builder.makeIntType(32);
2090 case glslang::EbtUint: return builder.makeUintType(32);
2091 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002092 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002093 return builder.makeFloatType(32);
2094 }
2095}
2096
John Kessenich8c8505c2016-07-26 12:50:38 -06002097// If node is a swizzle operation, return the type that should be used if
2098// the swizzle base is first consumed by another operation, before the swizzle
2099// is applied.
2100spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2101{
John Kessenichecba76f2017-01-06 00:34:48 -07002102 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002103 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2104 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2105 else
2106 return spv::NoType;
2107}
2108
2109// When inverting a swizzle with a parent op, this function
2110// will apply the swizzle operation to a completed parent operation.
2111spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2112{
2113 std::vector<unsigned> swizzle;
2114 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2115 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2116}
2117
John Kessenich8c8505c2016-07-26 12:50:38 -06002118// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2119void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2120{
2121 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2122 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2123 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2124}
2125
John Kessenich3ac051e2015-12-20 11:29:16 -07002126// Convert from a glslang type to an SPV type, by calling into a
2127// recursive version of this function. This establishes the inherited
2128// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002129spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2130{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002131 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002132}
2133
2134// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002135// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002136// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002137spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002138{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002139 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002140
2141 switch (type.getBasicType()) {
2142 case glslang::EbtVoid:
2143 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002144 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002145 break;
2146 case glslang::EbtFloat:
2147 spvType = builder.makeFloatType(32);
2148 break;
2149 case glslang::EbtDouble:
2150 spvType = builder.makeFloatType(64);
2151 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002152#ifdef AMD_EXTENSIONS
2153 case glslang::EbtFloat16:
2154 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002155 spvType = builder.makeFloatType(16);
2156 break;
2157#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002158 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002159 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2160 // a 32-bit int where non-0 means true.
2161 if (explicitLayout != glslang::ElpNone)
2162 spvType = builder.makeUintType(32);
2163 else
2164 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002165 break;
2166 case glslang::EbtInt:
2167 spvType = builder.makeIntType(32);
2168 break;
2169 case glslang::EbtUint:
2170 spvType = builder.makeUintType(32);
2171 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002172 case glslang::EbtInt64:
2173 builder.addCapability(spv::CapabilityInt64);
2174 spvType = builder.makeIntType(64);
2175 break;
2176 case glslang::EbtUint64:
2177 builder.addCapability(spv::CapabilityInt64);
2178 spvType = builder.makeUintType(64);
2179 break;
John Kessenich426394d2015-07-23 10:22:48 -06002180 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002181 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002182 spvType = builder.makeUintType(32);
2183 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002184 case glslang::EbtSampler:
2185 {
2186 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002187 if (sampler.sampler) {
2188 // pure sampler
2189 spvType = builder.makeSamplerType();
2190 } else {
2191 // an image is present, make its type
2192 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2193 sampler.image ? 2 : 1, TranslateImageFormat(type));
2194 if (sampler.combined) {
2195 // already has both image and sampler, make the combined type
2196 spvType = builder.makeSampledImageType(spvType);
2197 }
John Kessenich55e7d112015-11-15 21:33:39 -07002198 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002199 }
John Kessenich140f3df2015-06-26 16:58:36 -06002200 break;
2201 case glslang::EbtStruct:
2202 case glslang::EbtBlock:
2203 {
2204 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002205 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002206
2207 // Try to share structs for different layouts, but not yet for other
2208 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002209 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002210 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002211 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002212 break;
2213
2214 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002215 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002216 memberRemapper[glslangMembers].resize(glslangMembers->size());
2217 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002218 }
2219 break;
2220 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002221 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002222 break;
2223 }
2224
2225 if (type.isMatrix())
2226 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2227 else {
2228 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2229 if (type.getVectorSize() > 1)
2230 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2231 }
2232
2233 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002234 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2235
John Kessenichc9a80832015-09-12 12:17:44 -06002236 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002237 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002238 // We need to decorate array strides for types needing explicit layout, except blocks.
2239 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002240 // Use a dummy glslang type for querying internal strides of
2241 // arrays of arrays, but using just a one-dimensional array.
2242 glslang::TType simpleArrayType(type, 0); // deference type of the array
2243 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2244 simpleArrayType.getArraySizes().dereference();
2245
2246 // Will compute the higher-order strides here, rather than making a whole
2247 // pile of types and doing repetitive recursion on their contents.
2248 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2249 }
John Kessenichf8842e52016-01-04 19:22:56 -07002250
2251 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002252 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002253 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002254 if (stride > 0)
2255 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002256 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002257 }
2258 } else {
2259 // single-dimensional array, and don't yet have stride
2260
John Kessenichf8842e52016-01-04 19:22:56 -07002261 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002262 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2263 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002264 }
John Kessenich31ed4832015-09-09 17:51:38 -06002265
John Kessenichc9a80832015-09-12 12:17:44 -06002266 // Do the outer dimension, which might not be known for a runtime-sized array
2267 if (type.isRuntimeSizedArray()) {
2268 spvType = builder.makeRuntimeArray(spvType);
2269 } else {
2270 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002271 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002272 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002273 if (stride > 0)
2274 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002275 }
2276
2277 return spvType;
2278}
2279
John Kessenich0e737842017-03-24 18:38:16 -06002280// TODO: this functionality should exist at a higher level, in creating the AST
2281//
2282// Identify interface members that don't have their required extension turned on.
2283//
2284bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2285{
2286 auto& extensions = glslangIntermediate->getRequestedExtensions();
2287
Rex Xubcf291a2017-03-29 23:01:36 +08002288 if (member.getFieldName() == "gl_ViewportMask" &&
2289 extensions.find("GL_NV_viewport_array2") == extensions.end())
2290 return true;
2291 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2292 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2293 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002294 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2295 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2296 return true;
2297 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2298 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2299 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002300 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2301 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2302 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002303
2304 return false;
2305};
2306
John Kessenich6090df02016-06-30 21:18:02 -06002307// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2308// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2309// Mutually recursive with convertGlslangToSpvType().
2310spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2311 const glslang::TTypeList* glslangMembers,
2312 glslang::TLayoutPacking explicitLayout,
2313 const glslang::TQualifier& qualifier)
2314{
2315 // Create a vector of struct types for SPIR-V to consume
2316 std::vector<spv::Id> spvMembers;
2317 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2318 int locationOffset = 0; // for use across struct members, when they are called recursively
2319 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2320 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2321 if (glslangMember.hiddenMember()) {
2322 ++memberDelta;
2323 if (type.getBasicType() == glslang::EbtBlock)
2324 memberRemapper[glslangMembers][i] = -1;
2325 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002326 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002327 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002328 if (filterMember(glslangMember))
2329 continue;
2330 }
John Kessenich6090df02016-06-30 21:18:02 -06002331 // modify just this child's view of the qualifier
2332 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2333 InheritQualifiers(memberQualifier, qualifier);
2334
2335 // manually inherit location; it's more complex
2336 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2337 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2338 if (qualifier.hasLocation())
2339 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2340
2341 // recurse
2342 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2343 }
2344 }
2345
2346 // Make the SPIR-V type
2347 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002348 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002349 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2350
2351 // Decorate it
2352 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2353
2354 return spvType;
2355}
2356
2357void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2358 const glslang::TTypeList* glslangMembers,
2359 glslang::TLayoutPacking explicitLayout,
2360 const glslang::TQualifier& qualifier,
2361 spv::Id spvType)
2362{
2363 // Name and decorate the non-hidden members
2364 int offset = -1;
2365 int locationOffset = 0; // for use within the members of this struct
2366 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2367 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2368 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002369 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002370 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002371 if (filterMember(glslangMember))
2372 continue;
2373 }
John Kessenich6090df02016-06-30 21:18:02 -06002374
2375 // modify just this child's view of the qualifier
2376 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2377 InheritQualifiers(memberQualifier, qualifier);
2378
2379 // using -1 above to indicate a hidden member
2380 if (member >= 0) {
2381 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2382 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2383 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2384 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002385 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2386 type.getQualifier().storage == glslang::EvqVaryingOut) {
2387 if (type.getBasicType() == glslang::EbtBlock ||
2388 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002389 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2390 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2391 }
2392 }
2393 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2394
2395 if (qualifier.storage == glslang::EvqBuffer) {
2396 std::vector<spv::Decoration> memory;
2397 TranslateMemoryDecoration(memberQualifier, memory);
2398 for (unsigned int i = 0; i < memory.size(); ++i)
2399 addMemberDecoration(spvType, member, memory[i]);
2400 }
2401
John Kessenich2f47bc92016-06-30 21:47:35 -06002402 // Compute location decoration; tricky based on whether inheritance is at play and
2403 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002404 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2405 // probably move to the linker stage of the front end proper, and just have the
2406 // answer sitting already distributed throughout the individual member locations.
2407 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002408 // Ignore member locations if the container is an array, as that's
2409 // ill-specified and decisions have been made to not allow this anyway.
2410 // The object itself must have a location, and that comes out from decorating the object,
2411 // not the type (this code decorates types).
2412 if (! type.isArray()) {
2413 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2414 // struct members should not have explicit locations
2415 assert(type.getBasicType() != glslang::EbtStruct);
2416 location = memberQualifier.layoutLocation;
2417 } else if (type.getBasicType() != glslang::EbtBlock) {
2418 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2419 // The members, and their nested types, must not themselves have Location decorations.
2420 } else if (qualifier.hasLocation()) // inheritance
2421 location = qualifier.layoutLocation + locationOffset;
2422 }
John Kessenich6090df02016-06-30 21:18:02 -06002423 if (location >= 0)
2424 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2425
John Kessenich2f47bc92016-06-30 21:47:35 -06002426 if (qualifier.hasLocation()) // track for upcoming inheritance
2427 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2428
John Kessenich6090df02016-06-30 21:18:02 -06002429 // component, XFB, others
2430 if (glslangMember.getQualifier().hasComponent())
2431 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2432 if (glslangMember.getQualifier().hasXfbOffset())
2433 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2434 else if (explicitLayout != glslang::ElpNone) {
2435 // figure out what to do with offset, which is accumulating
2436 int nextOffset;
2437 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2438 if (offset >= 0)
2439 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2440 offset = nextOffset;
2441 }
2442
2443 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2444 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2445
2446 // built-in variable decorations
2447 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002448 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002449 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002450
2451#ifdef NV_EXTENSIONS
2452 if (builtIn == spv::BuiltInLayer) {
2453 // SPV_NV_viewport_array2 extension
2454 if (glslangMember.getQualifier().layoutViewportRelative){
2455 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2456 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2457 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2458 }
2459 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2460 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2461 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2462 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2463 }
2464 }
chaocdf3956c2017-02-14 14:52:34 -08002465 if (glslangMember.getQualifier().layoutPassthrough) {
2466 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2467 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2468 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2469 }
chaoc771d89f2017-01-13 01:10:53 -08002470#endif
John Kessenich6090df02016-06-30 21:18:02 -06002471 }
2472 }
2473
2474 // Decorate the structure
2475 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2476 addDecoration(spvType, TranslateBlockDecoration(type));
2477 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2478 builder.addCapability(spv::CapabilityGeometryStreams);
2479 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2480 }
2481 if (glslangIntermediate->getXfbMode()) {
2482 builder.addCapability(spv::CapabilityTransformFeedback);
2483 if (type.getQualifier().hasXfbStride())
2484 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2485 if (type.getQualifier().hasXfbBuffer())
2486 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2487 }
2488}
2489
John Kessenich6c292d32016-02-15 20:58:50 -07002490// Turn the expression forming the array size into an id.
2491// This is not quite trivial, because of specialization constants.
2492// Sometimes, a raw constant is turned into an Id, and sometimes
2493// a specialization constant expression is.
2494spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2495{
2496 // First, see if this is sized with a node, meaning a specialization constant:
2497 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2498 if (specNode != nullptr) {
2499 builder.clearAccessChain();
2500 specNode->traverse(this);
2501 return accessChainLoad(specNode->getAsTyped()->getType());
2502 }
qining25262b32016-05-06 17:25:16 -04002503
John Kessenich6c292d32016-02-15 20:58:50 -07002504 // Otherwise, need a compile-time (front end) size, get it:
2505 int size = arraySizes.getDimSize(dim);
2506 assert(size > 0);
2507 return builder.makeUintConstant(size);
2508}
2509
John Kessenich103bef92016-02-08 21:38:15 -07002510// Wrap the builder's accessChainLoad to:
2511// - localize handling of RelaxedPrecision
2512// - use the SPIR-V inferred type instead of another conversion of the glslang type
2513// (avoids unnecessary work and possible type punning for structures)
2514// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002515spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2516{
John Kessenich103bef92016-02-08 21:38:15 -07002517 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2518 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2519
2520 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002521 if (type.getBasicType() == glslang::EbtBool) {
2522 if (builder.isScalarType(nominalTypeId)) {
2523 // Conversion for bool
2524 spv::Id boolType = builder.makeBoolType();
2525 if (nominalTypeId != boolType)
2526 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2527 } else if (builder.isVectorType(nominalTypeId)) {
2528 // Conversion for bvec
2529 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2530 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2531 if (nominalTypeId != bvecType)
2532 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2533 }
2534 }
John Kessenich103bef92016-02-08 21:38:15 -07002535
2536 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002537}
2538
Rex Xu27253232016-02-23 17:51:09 +08002539// Wrap the builder's accessChainStore to:
2540// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002541//
2542// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002543void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2544{
2545 // Need to convert to abstract types when necessary
2546 if (type.getBasicType() == glslang::EbtBool) {
2547 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2548
2549 if (builder.isScalarType(nominalTypeId)) {
2550 // Conversion for bool
2551 spv::Id boolType = builder.makeBoolType();
2552 if (nominalTypeId != boolType) {
2553 spv::Id zero = builder.makeUintConstant(0);
2554 spv::Id one = builder.makeUintConstant(1);
2555 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2556 }
2557 } else if (builder.isVectorType(nominalTypeId)) {
2558 // Conversion for bvec
2559 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2560 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2561 if (nominalTypeId != bvecType) {
2562 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2563 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2564 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2565 }
2566 }
2567 }
2568
2569 builder.accessChainStore(rvalue);
2570}
2571
John Kessenich4bf71552016-09-02 11:20:21 -06002572// For storing when types match at the glslang level, but not might match at the
2573// SPIR-V level.
2574//
2575// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002576// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002577// as in a member-decorated way.
2578//
2579// NOTE: This function can handle any store request; if it's not special it
2580// simplifies to a simple OpStore.
2581//
2582// Implicitly uses the existing builder.accessChain as the storage target.
2583void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2584{
John Kessenichb3e24e42016-09-11 12:33:43 -06002585 // we only do the complex path here if it's an aggregate
2586 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002587 accessChainStore(type, rValue);
2588 return;
2589 }
2590
John Kessenichb3e24e42016-09-11 12:33:43 -06002591 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002592 spv::Id rType = builder.getTypeId(rValue);
2593 spv::Id lValue = builder.accessChainGetLValue();
2594 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2595 if (lType == rType) {
2596 accessChainStore(type, rValue);
2597 return;
2598 }
2599
John Kessenichb3e24e42016-09-11 12:33:43 -06002600 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002601 // where the two types were the same type in GLSL. This requires member
2602 // by member copy, recursively.
2603
John Kessenichb3e24e42016-09-11 12:33:43 -06002604 // If an array, copy element by element.
2605 if (type.isArray()) {
2606 glslang::TType glslangElementType(type, 0);
2607 spv::Id elementRType = builder.getContainedTypeId(rType);
2608 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2609 // get the source member
2610 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002611
John Kessenichb3e24e42016-09-11 12:33:43 -06002612 // set up the target storage
2613 builder.clearAccessChain();
2614 builder.setAccessChainLValue(lValue);
2615 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002616
John Kessenichb3e24e42016-09-11 12:33:43 -06002617 // store the member
2618 multiTypeStore(glslangElementType, elementRValue);
2619 }
2620 } else {
2621 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002622
John Kessenichb3e24e42016-09-11 12:33:43 -06002623 // loop over structure members
2624 const glslang::TTypeList& members = *type.getStruct();
2625 for (int m = 0; m < (int)members.size(); ++m) {
2626 const glslang::TType& glslangMemberType = *members[m].type;
2627
2628 // get the source member
2629 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2630 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2631
2632 // set up the target storage
2633 builder.clearAccessChain();
2634 builder.setAccessChainLValue(lValue);
2635 builder.accessChainPush(builder.makeIntConstant(m));
2636
2637 // store the member
2638 multiTypeStore(glslangMemberType, memberRValue);
2639 }
John Kessenich4bf71552016-09-02 11:20:21 -06002640 }
2641}
2642
John Kessenichf85e8062015-12-19 13:57:10 -07002643// Decide whether or not this type should be
2644// decorated with offsets and strides, and if so
2645// whether std140 or std430 rules should be applied.
2646glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002647{
John Kessenichf85e8062015-12-19 13:57:10 -07002648 // has to be a block
2649 if (type.getBasicType() != glslang::EbtBlock)
2650 return glslang::ElpNone;
2651
2652 // has to be a uniform or buffer block
2653 if (type.getQualifier().storage != glslang::EvqUniform &&
2654 type.getQualifier().storage != glslang::EvqBuffer)
2655 return glslang::ElpNone;
2656
2657 // return the layout to use
2658 switch (type.getQualifier().layoutPacking) {
2659 case glslang::ElpStd140:
2660 case glslang::ElpStd430:
2661 return type.getQualifier().layoutPacking;
2662 default:
2663 return glslang::ElpNone;
2664 }
John Kessenich31ed4832015-09-09 17:51:38 -06002665}
2666
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002667// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002668int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002669{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002670 int size;
John Kessenich49987892015-12-29 17:11:44 -07002671 int stride;
2672 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002673
2674 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002675}
2676
John Kessenich49987892015-12-29 17:11:44 -07002677// 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 -07002678// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002679int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002680{
John Kessenich49987892015-12-29 17:11:44 -07002681 glslang::TType elementType;
2682 elementType.shallowCopy(matrixType);
2683 elementType.clearArraySizes();
2684
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002685 int size;
John Kessenich49987892015-12-29 17:11:44 -07002686 int stride;
2687 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2688
2689 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002690}
2691
John Kessenich5e4b1242015-08-06 22:53:06 -06002692// Given a member type of a struct, realign the current offset for it, and compute
2693// the next (not yet aligned) offset for the next member, which will get aligned
2694// on the next call.
2695// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2696// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2697// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002698void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002699 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002700{
2701 // this will get a positive value when deemed necessary
2702 nextOffset = -1;
2703
John Kessenich5e4b1242015-08-06 22:53:06 -06002704 // override anything in currentOffset with user-set offset
2705 if (memberType.getQualifier().hasOffset())
2706 currentOffset = memberType.getQualifier().layoutOffset;
2707
2708 // It could be that current linker usage in glslang updated all the layoutOffset,
2709 // in which case the following code does not matter. But, that's not quite right
2710 // once cross-compilation unit GLSL validation is done, as the original user
2711 // settings are needed in layoutOffset, and then the following will come into play.
2712
John Kessenichf85e8062015-12-19 13:57:10 -07002713 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002714 if (! memberType.getQualifier().hasOffset())
2715 currentOffset = -1;
2716
2717 return;
2718 }
2719
John Kessenichf85e8062015-12-19 13:57:10 -07002720 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002721 if (currentOffset < 0)
2722 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002723
John Kessenich5e4b1242015-08-06 22:53:06 -06002724 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2725 // but possibly not yet correctly aligned.
2726
2727 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002728 int dummyStride;
2729 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002730
2731 // Adjust alignment for HLSL rules
2732 if (glslangIntermediate->usingHlslOFfsets() &&
2733 ! memberType.isArray() && memberType.isVector()) {
2734 int dummySize;
2735 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2736 if (componentAlignment <= 4)
2737 memberAlignment = componentAlignment;
2738 }
2739
2740 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002741 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002742
2743 // Bump up to vec4 if there is a bad straddle
2744 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2745 glslang::RoundToPow2(currentOffset, 16);
2746
John Kessenich5e4b1242015-08-06 22:53:06 -06002747 nextOffset = currentOffset + memberSize;
2748}
2749
David Netoa901ffe2016-06-08 14:11:40 +01002750void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002751{
David Netoa901ffe2016-06-08 14:11:40 +01002752 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2753 switch (glslangBuiltIn)
2754 {
2755 case glslang::EbvClipDistance:
2756 case glslang::EbvCullDistance:
2757 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002758#ifdef NV_EXTENSIONS
2759 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002760 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002761 case glslang::EbvViewportMaskNV:
2762 case glslang::EbvSecondaryPositionNV:
2763 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002764 case glslang::EbvPositionPerViewNV:
2765 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002766#endif
David Netoa901ffe2016-06-08 14:11:40 +01002767 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2768 // Alternately, we could just call this for any glslang built-in, since the
2769 // capability already guards against duplicates.
2770 TranslateBuiltInDecoration(glslangBuiltIn, false);
2771 break;
2772 default:
2773 // Capabilities were already generated when the struct was declared.
2774 break;
2775 }
John Kessenichebb50532016-05-16 19:22:05 -06002776}
2777
John Kessenich6fccb3c2016-09-19 16:01:41 -06002778bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002779{
John Kessenicheee9d532016-09-19 18:09:30 -06002780 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002781}
2782
2783// Make all the functions, skeletally, without actually visiting their bodies.
2784void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2785{
2786 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2787 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002788 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002789 continue;
2790
2791 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002792 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002793 //
qining25262b32016-05-06 17:25:16 -04002794 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002795 // function. What it is an address of varies:
2796 //
John Kessenich4bf71552016-09-02 11:20:21 -06002797 // - "in" parameters not marked as "const" can be written to without modifying the calling
2798 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002799 //
2800 // - "const in" parameters can just be the r-value, as no writes need occur.
2801 //
John Kessenich4bf71552016-09-02 11:20:21 -06002802 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2803 // 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 -06002804
2805 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002806 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002807 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2808
John Kessenich37789792017-03-21 23:56:40 -06002809 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName;
2810
John Kessenich140f3df2015-06-26 16:58:36 -06002811 for (int p = 0; p < (int)parameters.size(); ++p) {
2812 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2813 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002814 // can we pass by reference?
2815 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002816 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002817 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002818 (p == 0 && implicitThis)) // implicit 'this'
Jason Ekstranded15ef12016-06-08 13:54:48 -07002819 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2820 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002821 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2822 else
John Kessenich4bf71552016-09-02 11:20:21 -06002823 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002824 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002825 paramTypes.push_back(typeId);
2826 }
2827
2828 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002829 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2830 convertGlslangToSpvType(glslFunction->getType()),
2831 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002832 if (implicitThis)
2833 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002834
2835 // Track function to emit/call later
2836 functionMap[glslFunction->getName().c_str()] = function;
2837
2838 // Set the parameter id's
2839 for (int p = 0; p < (int)parameters.size(); ++p) {
2840 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2841 // give a name too
2842 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2843 }
2844 }
2845}
2846
2847// Process all the initializers, while skipping the functions and link objects
2848void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2849{
2850 builder.setBuildPoint(shaderEntry->getLastBlock());
2851 for (int i = 0; i < (int)initializers.size(); ++i) {
2852 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2853 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2854
2855 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002856 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002857 initializer->traverse(this);
2858 }
2859 }
2860}
2861
2862// Process all the functions, while skipping initializers.
2863void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2864{
2865 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2866 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002867 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002868 node->traverse(this);
2869 }
2870}
2871
2872void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2873{
qining25262b32016-05-06 17:25:16 -04002874 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002875 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002876 currentFunction = functionMap[node->getName().c_str()];
2877 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002878 builder.setBuildPoint(functionBlock);
2879}
2880
Rex Xu04db3f52015-09-16 11:44:02 +08002881void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002882{
Rex Xufc618912015-09-09 16:42:49 +08002883 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002884
2885 glslang::TSampler sampler = {};
2886 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002887 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002888 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2889 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2890 }
2891
John Kessenich140f3df2015-06-26 16:58:36 -06002892 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2893 builder.clearAccessChain();
2894 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002895
2896 // Special case l-value operands
2897 bool lvalue = false;
2898 switch (node.getOp()) {
2899 case glslang::EOpImageAtomicAdd:
2900 case glslang::EOpImageAtomicMin:
2901 case glslang::EOpImageAtomicMax:
2902 case glslang::EOpImageAtomicAnd:
2903 case glslang::EOpImageAtomicOr:
2904 case glslang::EOpImageAtomicXor:
2905 case glslang::EOpImageAtomicExchange:
2906 case glslang::EOpImageAtomicCompSwap:
2907 if (i == 0)
2908 lvalue = true;
2909 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002910 case glslang::EOpSparseImageLoad:
2911 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2912 lvalue = true;
2913 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002914 case glslang::EOpSparseTexture:
2915 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2916 lvalue = true;
2917 break;
2918 case glslang::EOpSparseTextureClamp:
2919 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2920 lvalue = true;
2921 break;
2922 case glslang::EOpSparseTextureLod:
2923 case glslang::EOpSparseTextureOffset:
2924 if (i == 3)
2925 lvalue = true;
2926 break;
2927 case glslang::EOpSparseTextureFetch:
2928 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2929 lvalue = true;
2930 break;
2931 case glslang::EOpSparseTextureFetchOffset:
2932 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2933 lvalue = true;
2934 break;
2935 case glslang::EOpSparseTextureLodOffset:
2936 case glslang::EOpSparseTextureGrad:
2937 case glslang::EOpSparseTextureOffsetClamp:
2938 if (i == 4)
2939 lvalue = true;
2940 break;
2941 case glslang::EOpSparseTextureGradOffset:
2942 case glslang::EOpSparseTextureGradClamp:
2943 if (i == 5)
2944 lvalue = true;
2945 break;
2946 case glslang::EOpSparseTextureGradOffsetClamp:
2947 if (i == 6)
2948 lvalue = true;
2949 break;
2950 case glslang::EOpSparseTextureGather:
2951 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2952 lvalue = true;
2953 break;
2954 case glslang::EOpSparseTextureGatherOffset:
2955 case glslang::EOpSparseTextureGatherOffsets:
2956 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2957 lvalue = true;
2958 break;
Rex Xufc618912015-09-09 16:42:49 +08002959 default:
2960 break;
2961 }
2962
Rex Xu6b86d492015-09-16 17:48:22 +08002963 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002964 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002965 else
John Kessenich32cfd492016-02-02 12:37:46 -07002966 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002967 }
2968}
2969
John Kessenichfc51d282015-08-19 13:34:18 -06002970void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002971{
John Kessenichfc51d282015-08-19 13:34:18 -06002972 builder.clearAccessChain();
2973 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002974 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002975}
John Kessenich140f3df2015-06-26 16:58:36 -06002976
John Kessenichfc51d282015-08-19 13:34:18 -06002977spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2978{
Rex Xufc618912015-09-09 16:42:49 +08002979 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002980 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002981 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002982 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002983
John Kessenichfc51d282015-08-19 13:34:18 -06002984 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002985 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2986 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2987 std::vector<spv::Id> arguments;
2988 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002989 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002990 else
2991 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002992 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002993
2994 spv::Builder::TextureParameters params = { };
2995 params.sampler = arguments[0];
2996
Rex Xu04db3f52015-09-16 11:44:02 +08002997 glslang::TCrackedTextureOp cracked;
2998 node->crackTexture(sampler, cracked);
2999
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003000 const bool isUnsignedResult =
3001 node->getType().getBasicType() == glslang::EbtUint64 ||
3002 node->getType().getBasicType() == glslang::EbtUint;
3003
John Kessenichfc51d282015-08-19 13:34:18 -06003004 // Check for queries
3005 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003006 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3007 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003008 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003009
John Kessenichfc51d282015-08-19 13:34:18 -06003010 switch (node->getOp()) {
3011 case glslang::EOpImageQuerySize:
3012 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003013 if (arguments.size() > 1) {
3014 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003015 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003016 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003017 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003018 case glslang::EOpImageQuerySamples:
3019 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003020 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003021 case glslang::EOpTextureQueryLod:
3022 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003023 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003024 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003025 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003026 case glslang::EOpSparseTexelsResident:
3027 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003028 default:
3029 assert(0);
3030 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003031 }
John Kessenich140f3df2015-06-26 16:58:36 -06003032 }
3033
Rex Xufc618912015-09-09 16:42:49 +08003034 // Check for image functions other than queries
3035 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003036 std::vector<spv::Id> operands;
3037 auto opIt = arguments.begin();
3038 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003039
3040 // Handle subpass operations
3041 // TODO: GLSL should change to have the "MS" only on the type rather than the
3042 // built-in function.
3043 if (cracked.subpass) {
3044 // add on the (0,0) coordinate
3045 spv::Id zero = builder.makeIntConstant(0);
3046 std::vector<spv::Id> comps;
3047 comps.push_back(zero);
3048 comps.push_back(zero);
3049 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3050 if (sampler.ms) {
3051 operands.push_back(spv::ImageOperandsSampleMask);
3052 operands.push_back(*(opIt++));
3053 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003054 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003055 }
3056
John Kessenich56bab042015-09-16 10:54:31 -06003057 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003058 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003059 if (sampler.ms) {
3060 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003061 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003062 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003063 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3064 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003065 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003066 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003067 if (sampler.ms) {
3068 operands.push_back(*(opIt + 1));
3069 operands.push_back(spv::ImageOperandsSampleMask);
3070 operands.push_back(*opIt);
3071 } else
3072 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003073 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003074 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3075 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003076 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003077 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3078 builder.addCapability(spv::CapabilitySparseResidency);
3079 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3080 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3081
3082 if (sampler.ms) {
3083 operands.push_back(spv::ImageOperandsSampleMask);
3084 operands.push_back(*opIt++);
3085 }
3086
3087 // Create the return type that was a special structure
3088 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003089 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003090 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3091 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3092
3093 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3094
3095 // Decode the return type
3096 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3097 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003098 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003099 // Process image atomic operations
3100
3101 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3102 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003103 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003104
John Kessenich8c8505c2016-07-26 12:50:38 -06003105 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003106 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003107
3108 std::vector<spv::Id> operands;
3109 operands.push_back(pointer);
3110 for (; opIt != arguments.end(); ++opIt)
3111 operands.push_back(*opIt);
3112
John Kessenich8c8505c2016-07-26 12:50:38 -06003113 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003114 }
3115 }
3116
3117 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003118 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003119 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3120
John Kessenichfc51d282015-08-19 13:34:18 -06003121 // check for bias argument
3122 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003123 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003124 int nonBiasArgCount = 2;
3125 if (cracked.offset)
3126 ++nonBiasArgCount;
3127 if (cracked.grad)
3128 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003129 if (cracked.lodClamp)
3130 ++nonBiasArgCount;
3131 if (sparse)
3132 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003133
3134 if ((int)arguments.size() > nonBiasArgCount)
3135 bias = true;
3136 }
3137
John Kessenicha5c33d62016-06-02 23:45:21 -06003138 // See if the sampler param should really be just the SPV image part
3139 if (cracked.fetch) {
3140 // a fetch needs to have the image extracted first
3141 if (builder.isSampledImage(params.sampler))
3142 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3143 }
3144
John Kessenichfc51d282015-08-19 13:34:18 -06003145 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003146
John Kessenichfc51d282015-08-19 13:34:18 -06003147 params.coords = arguments[1];
3148 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003149 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003150
3151 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003152 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003153 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003154 ++extraArgs;
3155 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003156 params.Dref = arguments[2];
3157 ++extraArgs;
3158 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003159 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003160 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003161 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003162 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003163 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003164 dRefComp = builder.getNumComponents(params.coords) - 1;
3165 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003166 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3167 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003168
3169 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003170 if (cracked.lod) {
3171 params.lod = arguments[2];
3172 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003173 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3174 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3175 noImplicitLod = true;
3176 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003177
3178 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003179 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003180 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003181 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003182 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003183
3184 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003185 if (cracked.grad) {
3186 params.gradX = arguments[2 + extraArgs];
3187 params.gradY = arguments[3 + extraArgs];
3188 extraArgs += 2;
3189 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003190
3191 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003192 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003193 params.offset = arguments[2 + extraArgs];
3194 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003195 } else if (cracked.offsets) {
3196 params.offsets = arguments[2 + extraArgs];
3197 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003198 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003199
3200 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003201 if (cracked.lodClamp) {
3202 params.lodClamp = arguments[2 + extraArgs];
3203 ++extraArgs;
3204 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003205
3206 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003207 if (sparse) {
3208 params.texelOut = arguments[2 + extraArgs];
3209 ++extraArgs;
3210 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003211
3212 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003213 if (bias) {
3214 params.bias = arguments[2 + extraArgs];
3215 ++extraArgs;
3216 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003217
3218 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003219 if (cracked.gather && ! sampler.shadow) {
3220 // default component is 0, if missing, otherwise an argument
3221 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003222 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003223 ++extraArgs;
3224 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003225 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003226 }
3227 }
John Kessenichfc51d282015-08-19 13:34:18 -06003228
John Kessenich65336482016-06-16 14:06:26 -06003229 // projective component (might not to move)
3230 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3231 // are divided by the last component of P."
3232 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3233 // unused components will appear after all used components."
3234 if (cracked.proj) {
3235 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3236 int projTargetComp;
3237 switch (sampler.dim) {
3238 case glslang::Esd1D: projTargetComp = 1; break;
3239 case glslang::Esd2D: projTargetComp = 2; break;
3240 case glslang::EsdRect: projTargetComp = 2; break;
3241 default: projTargetComp = projSourceComp; break;
3242 }
3243 // copy the projective coordinate if we have to
3244 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003245 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003246 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3247 projSourceComp);
3248 params.coords = builder.createCompositeInsert(projComp, params.coords,
3249 builder.getTypeId(params.coords), projTargetComp);
3250 }
3251 }
3252
John Kessenich8c8505c2016-07-26 12:50:38 -06003253 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003254}
3255
3256spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3257{
3258 // Grab the function's pointer from the previously created function
3259 spv::Function* function = functionMap[node->getName().c_str()];
3260 if (! function)
3261 return 0;
3262
3263 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3264 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3265
3266 // See comments in makeFunctions() for details about the semantics for parameter passing.
3267 //
3268 // These imply we need a four step process:
3269 // 1. Evaluate the arguments
3270 // 2. Allocate and make copies of in, out, and inout arguments
3271 // 3. Make the call
3272 // 4. Copy back the results
3273
3274 // 1. Evaluate the arguments
3275 std::vector<spv::Builder::AccessChain> lValues;
3276 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003277 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003278 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003279 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003280 // build l-value
3281 builder.clearAccessChain();
3282 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003283 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003284 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003285 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003286 // save l-value
3287 lValues.push_back(builder.getAccessChain());
3288 } else {
3289 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003290 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003291 }
3292 }
3293
3294 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3295 // copy the original into that space.
3296 //
3297 // Also, build up the list of actual arguments to pass in for the call
3298 int lValueCount = 0;
3299 int rValueCount = 0;
3300 std::vector<spv::Id> spvArgs;
3301 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003302 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003303 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003304 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003305 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3306 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003307 builder.setAccessChain(lValues[lValueCount]);
3308 arg = builder.accessChainGetLValue();
3309 ++lValueCount;
3310 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003311 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003312 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3313 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3314 // need to copy the input into output space
3315 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003316 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003317 builder.clearAccessChain();
3318 builder.setAccessChainLValue(arg);
3319 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003320 }
3321 ++lValueCount;
3322 } else {
3323 arg = rValues[rValueCount];
3324 ++rValueCount;
3325 }
3326 spvArgs.push_back(arg);
3327 }
3328
3329 // 3. Make the call.
3330 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003331 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003332
3333 // 4. Copy back out an "out" arguments.
3334 lValueCount = 0;
3335 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003336 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003337 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3338 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3339 spv::Id copy = builder.createLoad(spvArgs[a]);
3340 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003341 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003342 }
3343 ++lValueCount;
3344 }
3345 }
3346
3347 return result;
3348}
3349
3350// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003351spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3352 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003353 spv::Id typeId, spv::Id left, spv::Id right,
3354 glslang::TBasicType typeProxy, bool reduceComparison)
3355{
Rex Xu8ff43de2016-04-22 16:51:45 +08003356 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003357#ifdef AMD_EXTENSIONS
3358 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3359#else
John Kessenich140f3df2015-06-26 16:58:36 -06003360 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003361#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003362 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003363
3364 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003365 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003366 bool comparison = false;
3367
3368 switch (op) {
3369 case glslang::EOpAdd:
3370 case glslang::EOpAddAssign:
3371 if (isFloat)
3372 binOp = spv::OpFAdd;
3373 else
3374 binOp = spv::OpIAdd;
3375 break;
3376 case glslang::EOpSub:
3377 case glslang::EOpSubAssign:
3378 if (isFloat)
3379 binOp = spv::OpFSub;
3380 else
3381 binOp = spv::OpISub;
3382 break;
3383 case glslang::EOpMul:
3384 case glslang::EOpMulAssign:
3385 if (isFloat)
3386 binOp = spv::OpFMul;
3387 else
3388 binOp = spv::OpIMul;
3389 break;
3390 case glslang::EOpVectorTimesScalar:
3391 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003392 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003393 if (builder.isVector(right))
3394 std::swap(left, right);
3395 assert(builder.isScalar(right));
3396 needMatchingVectors = false;
3397 binOp = spv::OpVectorTimesScalar;
3398 } else
3399 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003400 break;
3401 case glslang::EOpVectorTimesMatrix:
3402 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003403 binOp = spv::OpVectorTimesMatrix;
3404 break;
3405 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003406 binOp = spv::OpMatrixTimesVector;
3407 break;
3408 case glslang::EOpMatrixTimesScalar:
3409 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003410 binOp = spv::OpMatrixTimesScalar;
3411 break;
3412 case glslang::EOpMatrixTimesMatrix:
3413 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003414 binOp = spv::OpMatrixTimesMatrix;
3415 break;
3416 case glslang::EOpOuterProduct:
3417 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003418 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003419 break;
3420
3421 case glslang::EOpDiv:
3422 case glslang::EOpDivAssign:
3423 if (isFloat)
3424 binOp = spv::OpFDiv;
3425 else if (isUnsigned)
3426 binOp = spv::OpUDiv;
3427 else
3428 binOp = spv::OpSDiv;
3429 break;
3430 case glslang::EOpMod:
3431 case glslang::EOpModAssign:
3432 if (isFloat)
3433 binOp = spv::OpFMod;
3434 else if (isUnsigned)
3435 binOp = spv::OpUMod;
3436 else
3437 binOp = spv::OpSMod;
3438 break;
3439 case glslang::EOpRightShift:
3440 case glslang::EOpRightShiftAssign:
3441 if (isUnsigned)
3442 binOp = spv::OpShiftRightLogical;
3443 else
3444 binOp = spv::OpShiftRightArithmetic;
3445 break;
3446 case glslang::EOpLeftShift:
3447 case glslang::EOpLeftShiftAssign:
3448 binOp = spv::OpShiftLeftLogical;
3449 break;
3450 case glslang::EOpAnd:
3451 case glslang::EOpAndAssign:
3452 binOp = spv::OpBitwiseAnd;
3453 break;
3454 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003455 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003456 binOp = spv::OpLogicalAnd;
3457 break;
3458 case glslang::EOpInclusiveOr:
3459 case glslang::EOpInclusiveOrAssign:
3460 binOp = spv::OpBitwiseOr;
3461 break;
3462 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003463 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003464 binOp = spv::OpLogicalOr;
3465 break;
3466 case glslang::EOpExclusiveOr:
3467 case glslang::EOpExclusiveOrAssign:
3468 binOp = spv::OpBitwiseXor;
3469 break;
3470 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003471 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003472 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003473 break;
3474
3475 case glslang::EOpLessThan:
3476 case glslang::EOpGreaterThan:
3477 case glslang::EOpLessThanEqual:
3478 case glslang::EOpGreaterThanEqual:
3479 case glslang::EOpEqual:
3480 case glslang::EOpNotEqual:
3481 case glslang::EOpVectorEqual:
3482 case glslang::EOpVectorNotEqual:
3483 comparison = true;
3484 break;
3485 default:
3486 break;
3487 }
3488
John Kessenich7c1aa102015-10-15 13:29:11 -06003489 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003490 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003491 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003492 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003493 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003494
3495 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003496 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003497 builder.promoteScalar(precision, left, right);
3498
qining25262b32016-05-06 17:25:16 -04003499 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3500 addDecoration(result, noContraction);
3501 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003502 }
3503
3504 if (! comparison)
3505 return 0;
3506
John Kessenich7c1aa102015-10-15 13:29:11 -06003507 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003508
John Kessenich4583b612016-08-07 19:14:22 -06003509 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3510 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003511 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003512
3513 switch (op) {
3514 case glslang::EOpLessThan:
3515 if (isFloat)
3516 binOp = spv::OpFOrdLessThan;
3517 else if (isUnsigned)
3518 binOp = spv::OpULessThan;
3519 else
3520 binOp = spv::OpSLessThan;
3521 break;
3522 case glslang::EOpGreaterThan:
3523 if (isFloat)
3524 binOp = spv::OpFOrdGreaterThan;
3525 else if (isUnsigned)
3526 binOp = spv::OpUGreaterThan;
3527 else
3528 binOp = spv::OpSGreaterThan;
3529 break;
3530 case glslang::EOpLessThanEqual:
3531 if (isFloat)
3532 binOp = spv::OpFOrdLessThanEqual;
3533 else if (isUnsigned)
3534 binOp = spv::OpULessThanEqual;
3535 else
3536 binOp = spv::OpSLessThanEqual;
3537 break;
3538 case glslang::EOpGreaterThanEqual:
3539 if (isFloat)
3540 binOp = spv::OpFOrdGreaterThanEqual;
3541 else if (isUnsigned)
3542 binOp = spv::OpUGreaterThanEqual;
3543 else
3544 binOp = spv::OpSGreaterThanEqual;
3545 break;
3546 case glslang::EOpEqual:
3547 case glslang::EOpVectorEqual:
3548 if (isFloat)
3549 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003550 else if (isBool)
3551 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003552 else
3553 binOp = spv::OpIEqual;
3554 break;
3555 case glslang::EOpNotEqual:
3556 case glslang::EOpVectorNotEqual:
3557 if (isFloat)
3558 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003559 else if (isBool)
3560 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003561 else
3562 binOp = spv::OpINotEqual;
3563 break;
3564 default:
3565 break;
3566 }
3567
qining25262b32016-05-06 17:25:16 -04003568 if (binOp != spv::OpNop) {
3569 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3570 addDecoration(result, noContraction);
3571 return builder.setPrecision(result, precision);
3572 }
John Kessenich140f3df2015-06-26 16:58:36 -06003573
3574 return 0;
3575}
3576
John Kessenich04bb8a02015-12-12 12:28:14 -07003577//
3578// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3579// These can be any of:
3580//
3581// matrix * scalar
3582// scalar * matrix
3583// matrix * matrix linear algebraic
3584// matrix * vector
3585// vector * matrix
3586// matrix * matrix componentwise
3587// matrix op matrix op in {+, -, /}
3588// matrix op scalar op in {+, -, /}
3589// scalar op matrix op in {+, -, /}
3590//
qining25262b32016-05-06 17:25:16 -04003591spv::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 -07003592{
3593 bool firstClass = true;
3594
3595 // First, handle first-class matrix operations (* and matrix/scalar)
3596 switch (op) {
3597 case spv::OpFDiv:
3598 if (builder.isMatrix(left) && builder.isScalar(right)) {
3599 // turn matrix / scalar into a multiply...
3600 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3601 op = spv::OpMatrixTimesScalar;
3602 } else
3603 firstClass = false;
3604 break;
3605 case spv::OpMatrixTimesScalar:
3606 if (builder.isMatrix(right))
3607 std::swap(left, right);
3608 assert(builder.isScalar(right));
3609 break;
3610 case spv::OpVectorTimesMatrix:
3611 assert(builder.isVector(left));
3612 assert(builder.isMatrix(right));
3613 break;
3614 case spv::OpMatrixTimesVector:
3615 assert(builder.isMatrix(left));
3616 assert(builder.isVector(right));
3617 break;
3618 case spv::OpMatrixTimesMatrix:
3619 assert(builder.isMatrix(left));
3620 assert(builder.isMatrix(right));
3621 break;
3622 default:
3623 firstClass = false;
3624 break;
3625 }
3626
qining25262b32016-05-06 17:25:16 -04003627 if (firstClass) {
3628 spv::Id result = builder.createBinOp(op, typeId, left, right);
3629 addDecoration(result, noContraction);
3630 return builder.setPrecision(result, precision);
3631 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003632
LoopDawg592860c2016-06-09 08:57:35 -06003633 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003634 // The result type of all of them is the same type as the (a) matrix operand.
3635 // The algorithm is to:
3636 // - break the matrix(es) into vectors
3637 // - smear any scalar to a vector
3638 // - do vector operations
3639 // - make a matrix out the vector results
3640 switch (op) {
3641 case spv::OpFAdd:
3642 case spv::OpFSub:
3643 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003644 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003645 case spv::OpFMul:
3646 {
3647 // one time set up...
3648 bool leftMat = builder.isMatrix(left);
3649 bool rightMat = builder.isMatrix(right);
3650 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3651 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3652 spv::Id scalarType = builder.getScalarTypeId(typeId);
3653 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3654 std::vector<spv::Id> results;
3655 spv::Id smearVec = spv::NoResult;
3656 if (builder.isScalar(left))
3657 smearVec = builder.smearScalar(precision, left, vecType);
3658 else if (builder.isScalar(right))
3659 smearVec = builder.smearScalar(precision, right, vecType);
3660
3661 // do each vector op
3662 for (unsigned int c = 0; c < numCols; ++c) {
3663 std::vector<unsigned int> indexes;
3664 indexes.push_back(c);
3665 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3666 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003667 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3668 addDecoration(result, noContraction);
3669 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003670 }
3671
3672 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003673 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003674 }
3675 default:
3676 assert(0);
3677 return spv::NoResult;
3678 }
3679}
3680
qining25262b32016-05-06 17:25:16 -04003681spv::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 -06003682{
3683 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003684 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003685 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003686 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003687#ifdef AMD_EXTENSIONS
3688 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3689#else
Rex Xu04db3f52015-09-16 11:44:02 +08003690 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003691#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003692
3693 switch (op) {
3694 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003695 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003696 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003697 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003698 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003699 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003700 unaryOp = spv::OpSNegate;
3701 break;
3702
3703 case glslang::EOpLogicalNot:
3704 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003705 unaryOp = spv::OpLogicalNot;
3706 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003707 case glslang::EOpBitwiseNot:
3708 unaryOp = spv::OpNot;
3709 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003710
John Kessenich140f3df2015-06-26 16:58:36 -06003711 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003712 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003713 break;
3714 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003715 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003716 break;
3717 case glslang::EOpTranspose:
3718 unaryOp = spv::OpTranspose;
3719 break;
3720
3721 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003722 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003723 break;
3724 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003725 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003726 break;
3727 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003728 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003729 break;
3730 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003731 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003732 break;
3733 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003734 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003735 break;
3736 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003737 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003738 break;
3739 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003740 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003741 break;
3742 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003743 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003744 break;
3745
3746 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003747 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003748 break;
3749 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003750 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003751 break;
3752 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003753 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003754 break;
3755 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003756 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003757 break;
3758 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003759 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003760 break;
3761 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003762 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003763 break;
3764
3765 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003766 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003767 break;
3768 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003769 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003770 break;
3771
3772 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003773 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003774 break;
3775 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003776 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003777 break;
3778 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003779 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003780 break;
3781 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003782 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003783 break;
3784 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003785 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003786 break;
3787 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003788 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003789 break;
3790
3791 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003792 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003793 break;
3794 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003795 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003796 break;
3797 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003798 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003799 break;
3800 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003801 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003802 break;
3803 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003804 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003805 break;
3806 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003807 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003808 break;
3809
3810 case glslang::EOpIsNan:
3811 unaryOp = spv::OpIsNan;
3812 break;
3813 case glslang::EOpIsInf:
3814 unaryOp = spv::OpIsInf;
3815 break;
LoopDawg592860c2016-06-09 08:57:35 -06003816 case glslang::EOpIsFinite:
3817 unaryOp = spv::OpIsFinite;
3818 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003819
Rex Xucbc426e2015-12-15 16:03:10 +08003820 case glslang::EOpFloatBitsToInt:
3821 case glslang::EOpFloatBitsToUint:
3822 case glslang::EOpIntBitsToFloat:
3823 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003824 case glslang::EOpDoubleBitsToInt64:
3825 case glslang::EOpDoubleBitsToUint64:
3826 case glslang::EOpInt64BitsToDouble:
3827 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003828 unaryOp = spv::OpBitcast;
3829 break;
3830
John Kessenich140f3df2015-06-26 16:58:36 -06003831 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003832 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003833 break;
3834 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003835 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003836 break;
3837 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003838 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003839 break;
3840 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003841 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003842 break;
3843 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003844 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003845 break;
3846 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003847 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003848 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003849 case glslang::EOpPackSnorm4x8:
3850 libCall = spv::GLSLstd450PackSnorm4x8;
3851 break;
3852 case glslang::EOpUnpackSnorm4x8:
3853 libCall = spv::GLSLstd450UnpackSnorm4x8;
3854 break;
3855 case glslang::EOpPackUnorm4x8:
3856 libCall = spv::GLSLstd450PackUnorm4x8;
3857 break;
3858 case glslang::EOpUnpackUnorm4x8:
3859 libCall = spv::GLSLstd450UnpackUnorm4x8;
3860 break;
3861 case glslang::EOpPackDouble2x32:
3862 libCall = spv::GLSLstd450PackDouble2x32;
3863 break;
3864 case glslang::EOpUnpackDouble2x32:
3865 libCall = spv::GLSLstd450UnpackDouble2x32;
3866 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003867
Rex Xu8ff43de2016-04-22 16:51:45 +08003868 case glslang::EOpPackInt2x32:
3869 case glslang::EOpUnpackInt2x32:
3870 case glslang::EOpPackUint2x32:
3871 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003872 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003873 break;
3874
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003875#ifdef AMD_EXTENSIONS
3876 case glslang::EOpPackFloat2x16:
3877 case glslang::EOpUnpackFloat2x16:
3878 unaryOp = spv::OpBitcast;
3879 break;
3880#endif
3881
John Kessenich140f3df2015-06-26 16:58:36 -06003882 case glslang::EOpDPdx:
3883 unaryOp = spv::OpDPdx;
3884 break;
3885 case glslang::EOpDPdy:
3886 unaryOp = spv::OpDPdy;
3887 break;
3888 case glslang::EOpFwidth:
3889 unaryOp = spv::OpFwidth;
3890 break;
3891 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003892 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003893 unaryOp = spv::OpDPdxFine;
3894 break;
3895 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003896 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003897 unaryOp = spv::OpDPdyFine;
3898 break;
3899 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003900 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003901 unaryOp = spv::OpFwidthFine;
3902 break;
3903 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003904 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003905 unaryOp = spv::OpDPdxCoarse;
3906 break;
3907 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003908 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003909 unaryOp = spv::OpDPdyCoarse;
3910 break;
3911 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003912 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003913 unaryOp = spv::OpFwidthCoarse;
3914 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003915 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003916 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003917 libCall = spv::GLSLstd450InterpolateAtCentroid;
3918 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003919 case glslang::EOpAny:
3920 unaryOp = spv::OpAny;
3921 break;
3922 case glslang::EOpAll:
3923 unaryOp = spv::OpAll;
3924 break;
3925
3926 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003927 if (isFloat)
3928 libCall = spv::GLSLstd450FAbs;
3929 else
3930 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003931 break;
3932 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003933 if (isFloat)
3934 libCall = spv::GLSLstd450FSign;
3935 else
3936 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003937 break;
3938
John Kessenichfc51d282015-08-19 13:34:18 -06003939 case glslang::EOpAtomicCounterIncrement:
3940 case glslang::EOpAtomicCounterDecrement:
3941 case glslang::EOpAtomicCounter:
3942 {
3943 // Handle all of the atomics in one place, in createAtomicOperation()
3944 std::vector<spv::Id> operands;
3945 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003946 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003947 }
3948
John Kessenichfc51d282015-08-19 13:34:18 -06003949 case glslang::EOpBitFieldReverse:
3950 unaryOp = spv::OpBitReverse;
3951 break;
3952 case glslang::EOpBitCount:
3953 unaryOp = spv::OpBitCount;
3954 break;
3955 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003956 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003957 break;
3958 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003959 if (isUnsigned)
3960 libCall = spv::GLSLstd450FindUMsb;
3961 else
3962 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003963 break;
3964
Rex Xu574ab042016-04-14 16:53:07 +08003965 case glslang::EOpBallot:
3966 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003967 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003968 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003969 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003970#ifdef AMD_EXTENSIONS
3971 case glslang::EOpMinInvocations:
3972 case glslang::EOpMaxInvocations:
3973 case glslang::EOpAddInvocations:
3974 case glslang::EOpMinInvocationsNonUniform:
3975 case glslang::EOpMaxInvocationsNonUniform:
3976 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08003977 case glslang::EOpMinInvocationsInclusiveScan:
3978 case glslang::EOpMaxInvocationsInclusiveScan:
3979 case glslang::EOpAddInvocationsInclusiveScan:
3980 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
3981 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
3982 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
3983 case glslang::EOpMinInvocationsExclusiveScan:
3984 case glslang::EOpMaxInvocationsExclusiveScan:
3985 case glslang::EOpAddInvocationsExclusiveScan:
3986 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
3987 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
3988 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08003989#endif
Rex Xu51596642016-09-21 18:56:12 +08003990 {
3991 std::vector<spv::Id> operands;
3992 operands.push_back(operand);
3993 return createInvocationsOperation(op, typeId, operands, typeProxy);
3994 }
Rex Xu9d93a232016-05-05 12:30:44 +08003995
3996#ifdef AMD_EXTENSIONS
3997 case glslang::EOpMbcnt:
3998 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3999 libCall = spv::MbcntAMD;
4000 break;
4001
4002 case glslang::EOpCubeFaceIndex:
4003 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4004 libCall = spv::CubeFaceIndexAMD;
4005 break;
4006
4007 case glslang::EOpCubeFaceCoord:
4008 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4009 libCall = spv::CubeFaceCoordAMD;
4010 break;
4011#endif
Rex Xu338b1852016-05-05 20:38:33 +08004012
John Kessenich140f3df2015-06-26 16:58:36 -06004013 default:
4014 return 0;
4015 }
4016
4017 spv::Id id;
4018 if (libCall >= 0) {
4019 std::vector<spv::Id> args;
4020 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004021 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004022 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004023 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004024 }
John Kessenich140f3df2015-06-26 16:58:36 -06004025
qining25262b32016-05-06 17:25:16 -04004026 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004027 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004028}
4029
John Kessenich7a53f762016-01-20 11:19:27 -07004030// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004031spv::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 -07004032{
4033 // Handle unary operations vector by vector.
4034 // The result type is the same type as the original type.
4035 // The algorithm is to:
4036 // - break the matrix into vectors
4037 // - apply the operation to each vector
4038 // - make a matrix out the vector results
4039
4040 // get the types sorted out
4041 int numCols = builder.getNumColumns(operand);
4042 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004043 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4044 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004045 std::vector<spv::Id> results;
4046
4047 // do each vector op
4048 for (int c = 0; c < numCols; ++c) {
4049 std::vector<unsigned int> indexes;
4050 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004051 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4052 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4053 addDecoration(destVec, noContraction);
4054 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004055 }
4056
4057 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004058 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004059}
4060
Rex Xu73e3ce72016-04-27 18:48:17 +08004061spv::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 -06004062{
4063 spv::Op convOp = spv::OpNop;
4064 spv::Id zero = 0;
4065 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004066 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004067
4068 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4069
4070 switch (op) {
4071 case glslang::EOpConvIntToBool:
4072 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004073 case glslang::EOpConvInt64ToBool:
4074 case glslang::EOpConvUint64ToBool:
4075 zero = (op == glslang::EOpConvInt64ToBool ||
4076 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004077 zero = makeSmearedConstant(zero, vectorSize);
4078 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4079
4080 case glslang::EOpConvFloatToBool:
4081 zero = builder.makeFloatConstant(0.0F);
4082 zero = makeSmearedConstant(zero, vectorSize);
4083 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4084
4085 case glslang::EOpConvDoubleToBool:
4086 zero = builder.makeDoubleConstant(0.0);
4087 zero = makeSmearedConstant(zero, vectorSize);
4088 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4089
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004090#ifdef AMD_EXTENSIONS
4091 case glslang::EOpConvFloat16ToBool:
4092 zero = builder.makeFloat16Constant(0.0F);
4093 zero = makeSmearedConstant(zero, vectorSize);
4094 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4095#endif
4096
John Kessenich140f3df2015-06-26 16:58:36 -06004097 case glslang::EOpConvBoolToFloat:
4098 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004099 zero = builder.makeFloatConstant(0.0F);
4100 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004101 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004102
John Kessenich140f3df2015-06-26 16:58:36 -06004103 case glslang::EOpConvBoolToDouble:
4104 convOp = spv::OpSelect;
4105 zero = builder.makeDoubleConstant(0.0);
4106 one = builder.makeDoubleConstant(1.0);
4107 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004108
4109#ifdef AMD_EXTENSIONS
4110 case glslang::EOpConvBoolToFloat16:
4111 convOp = spv::OpSelect;
4112 zero = builder.makeFloat16Constant(0.0F);
4113 one = builder.makeFloat16Constant(1.0F);
4114 break;
4115#endif
4116
John Kessenich140f3df2015-06-26 16:58:36 -06004117 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004118 case glslang::EOpConvBoolToInt64:
4119 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4120 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004121 convOp = spv::OpSelect;
4122 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004123
John Kessenich140f3df2015-06-26 16:58:36 -06004124 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004125 case glslang::EOpConvBoolToUint64:
4126 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4127 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004128 convOp = spv::OpSelect;
4129 break;
4130
4131 case glslang::EOpConvIntToFloat:
4132 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004133 case glslang::EOpConvInt64ToFloat:
4134 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004135#ifdef AMD_EXTENSIONS
4136 case glslang::EOpConvIntToFloat16:
4137 case glslang::EOpConvInt64ToFloat16:
4138#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004139 convOp = spv::OpConvertSToF;
4140 break;
4141
4142 case glslang::EOpConvUintToFloat:
4143 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004144 case glslang::EOpConvUint64ToFloat:
4145 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004146#ifdef AMD_EXTENSIONS
4147 case glslang::EOpConvUintToFloat16:
4148 case glslang::EOpConvUint64ToFloat16:
4149#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004150 convOp = spv::OpConvertUToF;
4151 break;
4152
4153 case glslang::EOpConvDoubleToFloat:
4154 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004155#ifdef AMD_EXTENSIONS
4156 case glslang::EOpConvDoubleToFloat16:
4157 case glslang::EOpConvFloat16ToDouble:
4158 case glslang::EOpConvFloatToFloat16:
4159 case glslang::EOpConvFloat16ToFloat:
4160#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004161 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004162 if (builder.isMatrixType(destType))
4163 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004164 break;
4165
4166 case glslang::EOpConvFloatToInt:
4167 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004168 case glslang::EOpConvFloatToInt64:
4169 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004170#ifdef AMD_EXTENSIONS
4171 case glslang::EOpConvFloat16ToInt:
4172 case glslang::EOpConvFloat16ToInt64:
4173#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004174 convOp = spv::OpConvertFToS;
4175 break;
4176
4177 case glslang::EOpConvUintToInt:
4178 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004179 case glslang::EOpConvUint64ToInt64:
4180 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004181 if (builder.isInSpecConstCodeGenMode()) {
4182 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004183 zero = (op == glslang::EOpConvUint64ToInt64 ||
4184 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004185 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004186 // Use OpIAdd, instead of OpBitcast to do the conversion when
4187 // generating for OpSpecConstantOp instruction.
4188 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4189 }
4190 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004191 convOp = spv::OpBitcast;
4192 break;
4193
4194 case glslang::EOpConvFloatToUint:
4195 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004196 case glslang::EOpConvFloatToUint64:
4197 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004198#ifdef AMD_EXTENSIONS
4199 case glslang::EOpConvFloat16ToUint:
4200 case glslang::EOpConvFloat16ToUint64:
4201#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004202 convOp = spv::OpConvertFToU;
4203 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004204
4205 case glslang::EOpConvIntToInt64:
4206 case glslang::EOpConvInt64ToInt:
4207 convOp = spv::OpSConvert;
4208 break;
4209
4210 case glslang::EOpConvUintToUint64:
4211 case glslang::EOpConvUint64ToUint:
4212 convOp = spv::OpUConvert;
4213 break;
4214
4215 case glslang::EOpConvIntToUint64:
4216 case glslang::EOpConvInt64ToUint:
4217 case glslang::EOpConvUint64ToInt:
4218 case glslang::EOpConvUintToInt64:
4219 // OpSConvert/OpUConvert + OpBitCast
4220 switch (op) {
4221 case glslang::EOpConvIntToUint64:
4222 convOp = spv::OpSConvert;
4223 type = builder.makeIntType(64);
4224 break;
4225 case glslang::EOpConvInt64ToUint:
4226 convOp = spv::OpSConvert;
4227 type = builder.makeIntType(32);
4228 break;
4229 case glslang::EOpConvUint64ToInt:
4230 convOp = spv::OpUConvert;
4231 type = builder.makeUintType(32);
4232 break;
4233 case glslang::EOpConvUintToInt64:
4234 convOp = spv::OpUConvert;
4235 type = builder.makeUintType(64);
4236 break;
4237 default:
4238 assert(0);
4239 break;
4240 }
4241
4242 if (vectorSize > 0)
4243 type = builder.makeVectorType(type, vectorSize);
4244
4245 operand = builder.createUnaryOp(convOp, type, operand);
4246
4247 if (builder.isInSpecConstCodeGenMode()) {
4248 // Build zero scalar or vector for OpIAdd.
4249 zero = (op == glslang::EOpConvIntToUint64 ||
4250 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4251 zero = makeSmearedConstant(zero, vectorSize);
4252 // Use OpIAdd, instead of OpBitcast to do the conversion when
4253 // generating for OpSpecConstantOp instruction.
4254 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4255 }
4256 // For normal run-time conversion instruction, use OpBitcast.
4257 convOp = spv::OpBitcast;
4258 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004259 default:
4260 break;
4261 }
4262
4263 spv::Id result = 0;
4264 if (convOp == spv::OpNop)
4265 return result;
4266
4267 if (convOp == spv::OpSelect) {
4268 zero = makeSmearedConstant(zero, vectorSize);
4269 one = makeSmearedConstant(one, vectorSize);
4270 result = builder.createTriOp(convOp, destType, operand, one, zero);
4271 } else
4272 result = builder.createUnaryOp(convOp, destType, operand);
4273
John Kessenich32cfd492016-02-02 12:37:46 -07004274 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004275}
4276
4277spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4278{
4279 if (vectorSize == 0)
4280 return constant;
4281
4282 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4283 std::vector<spv::Id> components;
4284 for (int c = 0; c < vectorSize; ++c)
4285 components.push_back(constant);
4286 return builder.makeCompositeConstant(vectorTypeId, components);
4287}
4288
John Kessenich426394d2015-07-23 10:22:48 -06004289// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004290spv::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 -06004291{
4292 spv::Op opCode = spv::OpNop;
4293
4294 switch (op) {
4295 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004296 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004297 opCode = spv::OpAtomicIAdd;
4298 break;
4299 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004300 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004301 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004302 break;
4303 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004304 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004305 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004306 break;
4307 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004308 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004309 opCode = spv::OpAtomicAnd;
4310 break;
4311 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004312 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004313 opCode = spv::OpAtomicOr;
4314 break;
4315 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004316 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004317 opCode = spv::OpAtomicXor;
4318 break;
4319 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004320 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004321 opCode = spv::OpAtomicExchange;
4322 break;
4323 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004324 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004325 opCode = spv::OpAtomicCompareExchange;
4326 break;
4327 case glslang::EOpAtomicCounterIncrement:
4328 opCode = spv::OpAtomicIIncrement;
4329 break;
4330 case glslang::EOpAtomicCounterDecrement:
4331 opCode = spv::OpAtomicIDecrement;
4332 break;
4333 case glslang::EOpAtomicCounter:
4334 opCode = spv::OpAtomicLoad;
4335 break;
4336 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004337 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004338 break;
4339 }
4340
4341 // Sort out the operands
4342 // - mapping from glslang -> SPV
4343 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004344 // - compare-exchange swaps the value and comparator
4345 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004346 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4347 auto opIt = operands.begin(); // walk the glslang operands
4348 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004349 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4350 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4351 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004352 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4353 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004354 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004355 spvAtomicOperands.push_back(*(opIt + 1));
4356 spvAtomicOperands.push_back(*opIt);
4357 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004358 }
John Kessenich426394d2015-07-23 10:22:48 -06004359
John Kessenich3e60a6f2015-09-14 22:45:16 -06004360 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004361 for (; opIt != operands.end(); ++opIt)
4362 spvAtomicOperands.push_back(*opIt);
4363
4364 return builder.createOp(opCode, typeId, spvAtomicOperands);
4365}
4366
John Kessenich91cef522016-05-05 16:45:40 -06004367// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004368spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004369{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004370#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004371 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004372 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004373#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004374
Rex Xu51596642016-09-21 18:56:12 +08004375 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004376 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004377 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4378
chaocf200da82016-12-20 12:44:35 -08004379 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4380 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004381 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4382 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004383 } else if (op == glslang::EOpAnyInvocation ||
4384 op == glslang::EOpAllInvocations ||
4385 op == glslang::EOpAllInvocationsEqual) {
4386 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4387 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004388 } else {
4389 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004390#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004391 if (op == glslang::EOpMinInvocationsNonUniform ||
4392 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004393 op == glslang::EOpAddInvocationsNonUniform ||
4394 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4395 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4396 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4397 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4398 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4399 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004400 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004401#endif
Rex Xu51596642016-09-21 18:56:12 +08004402
4403 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004404#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004405 switch (op) {
4406 case glslang::EOpMinInvocations:
4407 case glslang::EOpMaxInvocations:
4408 case glslang::EOpAddInvocations:
4409 case glslang::EOpMinInvocationsNonUniform:
4410 case glslang::EOpMaxInvocationsNonUniform:
4411 case glslang::EOpAddInvocationsNonUniform:
4412 groupOperation = spv::GroupOperationReduce;
4413 spvGroupOperands.push_back(groupOperation);
4414 break;
4415 case glslang::EOpMinInvocationsInclusiveScan:
4416 case glslang::EOpMaxInvocationsInclusiveScan:
4417 case glslang::EOpAddInvocationsInclusiveScan:
4418 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4419 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4420 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4421 groupOperation = spv::GroupOperationInclusiveScan;
4422 spvGroupOperands.push_back(groupOperation);
4423 break;
4424 case glslang::EOpMinInvocationsExclusiveScan:
4425 case glslang::EOpMaxInvocationsExclusiveScan:
4426 case glslang::EOpAddInvocationsExclusiveScan:
4427 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4428 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4429 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4430 groupOperation = spv::GroupOperationExclusiveScan;
4431 spvGroupOperands.push_back(groupOperation);
4432 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004433 default:
4434 break;
Rex Xu430ef402016-10-14 17:22:23 +08004435 }
Rex Xu9d93a232016-05-05 12:30:44 +08004436#endif
Rex Xu51596642016-09-21 18:56:12 +08004437 }
4438
4439 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4440 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004441
4442 switch (op) {
4443 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004444 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004445 break;
John Kessenich91cef522016-05-05 16:45:40 -06004446 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004447 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004448 break;
John Kessenich91cef522016-05-05 16:45:40 -06004449 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004450 opCode = spv::OpSubgroupAllEqualKHR;
4451 break;
Rex Xu51596642016-09-21 18:56:12 +08004452 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004453 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004454 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004455 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004456 break;
4457 case glslang::EOpReadFirstInvocation:
4458 opCode = spv::OpSubgroupFirstInvocationKHR;
4459 break;
4460 case glslang::EOpBallot:
4461 {
4462 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4463 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4464 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4465 //
4466 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4467 //
4468 spv::Id uintType = builder.makeUintType(32);
4469 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4470 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4471
4472 std::vector<spv::Id> components;
4473 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4474 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4475
4476 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4477 return builder.createUnaryOp(spv::OpBitcast, typeId,
4478 builder.createCompositeConstruct(uvec2Type, components));
4479 }
4480
Rex Xu9d93a232016-05-05 12:30:44 +08004481#ifdef AMD_EXTENSIONS
4482 case glslang::EOpMinInvocations:
4483 case glslang::EOpMaxInvocations:
4484 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004485 case glslang::EOpMinInvocationsInclusiveScan:
4486 case glslang::EOpMaxInvocationsInclusiveScan:
4487 case glslang::EOpAddInvocationsInclusiveScan:
4488 case glslang::EOpMinInvocationsExclusiveScan:
4489 case glslang::EOpMaxInvocationsExclusiveScan:
4490 case glslang::EOpAddInvocationsExclusiveScan:
4491 if (op == glslang::EOpMinInvocations ||
4492 op == glslang::EOpMinInvocationsInclusiveScan ||
4493 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004494 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004495 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004496 else {
4497 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004498 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004499 else
Rex Xu51596642016-09-21 18:56:12 +08004500 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004501 }
Rex Xu430ef402016-10-14 17:22:23 +08004502 } else if (op == glslang::EOpMaxInvocations ||
4503 op == glslang::EOpMaxInvocationsInclusiveScan ||
4504 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004505 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004506 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004507 else {
4508 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004509 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004510 else
Rex Xu51596642016-09-21 18:56:12 +08004511 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004512 }
4513 } else {
4514 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004515 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004516 else
Rex Xu51596642016-09-21 18:56:12 +08004517 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004518 }
4519
Rex Xu2bbbe062016-08-23 15:41:05 +08004520 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004521 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004522
4523 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004524 case glslang::EOpMinInvocationsNonUniform:
4525 case glslang::EOpMaxInvocationsNonUniform:
4526 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004527 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4528 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4529 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4530 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4531 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4532 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4533 if (op == glslang::EOpMinInvocationsNonUniform ||
4534 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4535 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004536 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004537 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004538 else {
4539 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004540 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004541 else
Rex Xu51596642016-09-21 18:56:12 +08004542 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004543 }
4544 }
Rex Xu430ef402016-10-14 17:22:23 +08004545 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4546 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4547 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004548 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004549 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004550 else {
4551 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004552 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004553 else
Rex Xu51596642016-09-21 18:56:12 +08004554 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004555 }
4556 }
4557 else {
4558 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004559 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004560 else
Rex Xu51596642016-09-21 18:56:12 +08004561 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004562 }
4563
Rex Xu2bbbe062016-08-23 15:41:05 +08004564 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004565 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004566
4567 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004568#endif
John Kessenich91cef522016-05-05 16:45:40 -06004569 default:
4570 logger->missingFunctionality("invocation operation");
4571 return spv::NoResult;
4572 }
Rex Xu51596642016-09-21 18:56:12 +08004573
4574 assert(opCode != spv::OpNop);
4575 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004576}
4577
Rex Xu2bbbe062016-08-23 15:41:05 +08004578// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004579spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004580{
Rex Xub7072052016-09-26 15:53:40 +08004581#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004582 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4583 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004584 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004585 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004586 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4587 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4588 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004589#else
4590 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4591 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004592 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4593 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004594#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004595
4596 // Handle group invocation operations scalar by scalar.
4597 // The result type is the same type as the original type.
4598 // The algorithm is to:
4599 // - break the vector into scalars
4600 // - apply the operation to each scalar
4601 // - make a vector out the scalar results
4602
4603 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004604 int numComponents = builder.getNumComponents(operands[0]);
4605 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004606 std::vector<spv::Id> results;
4607
4608 // do each scalar op
4609 for (int comp = 0; comp < numComponents; ++comp) {
4610 std::vector<unsigned int> indexes;
4611 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004612 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004613 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004614 if (op == spv::OpSubgroupReadInvocationKHR) {
4615 spvGroupOperands.push_back(scalar);
4616 spvGroupOperands.push_back(operands[1]);
4617 } else if (op == spv::OpGroupBroadcast) {
4618 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004619 spvGroupOperands.push_back(scalar);
4620 spvGroupOperands.push_back(operands[1]);
4621 } else {
chaocf200da82016-12-20 12:44:35 -08004622 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004623 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004624 spvGroupOperands.push_back(scalar);
4625 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004626
Rex Xub7072052016-09-26 15:53:40 +08004627 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004628 }
4629
4630 // put the pieces together
4631 return builder.createCompositeConstruct(typeId, results);
4632}
Rex Xu2bbbe062016-08-23 15:41:05 +08004633
John Kessenich5e4b1242015-08-06 22:53:06 -06004634spv::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 -06004635{
Rex Xu8ff43de2016-04-22 16:51:45 +08004636 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004637#ifdef AMD_EXTENSIONS
4638 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4639#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004640 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004641#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004642
John Kessenich140f3df2015-06-26 16:58:36 -06004643 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004644 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004645 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004646 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004647 spv::Id typeId0 = 0;
4648 if (consumedOperands > 0)
4649 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08004650 spv::Id typeId1 = 0;
4651 if (consumedOperands > 1)
4652 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07004653 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004654
4655 switch (op) {
4656 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004657 if (isFloat)
4658 libCall = spv::GLSLstd450FMin;
4659 else if (isUnsigned)
4660 libCall = spv::GLSLstd450UMin;
4661 else
4662 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004663 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004664 break;
4665 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004666 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004667 break;
4668 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004669 if (isFloat)
4670 libCall = spv::GLSLstd450FMax;
4671 else if (isUnsigned)
4672 libCall = spv::GLSLstd450UMax;
4673 else
4674 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004675 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004676 break;
4677 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004678 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004679 break;
4680 case glslang::EOpDot:
4681 opCode = spv::OpDot;
4682 break;
4683 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004684 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004685 break;
4686
4687 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004688 if (isFloat)
4689 libCall = spv::GLSLstd450FClamp;
4690 else if (isUnsigned)
4691 libCall = spv::GLSLstd450UClamp;
4692 else
4693 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004694 builder.promoteScalar(precision, operands.front(), operands[1]);
4695 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004696 break;
4697 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004698 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4699 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004700 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004701 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004702 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004703 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004704 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004705 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004706 break;
4707 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004708 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004709 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004710 break;
4711 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004712 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004713 builder.promoteScalar(precision, operands[0], operands[2]);
4714 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004715 break;
4716
4717 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004718 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004719 break;
4720 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004721 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004722 break;
4723 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004724 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004725 break;
4726 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004727 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004728 break;
4729 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004730 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004731 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004732 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004733 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004734 libCall = spv::GLSLstd450InterpolateAtSample;
4735 break;
4736 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004737 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004738 libCall = spv::GLSLstd450InterpolateAtOffset;
4739 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004740 case glslang::EOpAddCarry:
4741 opCode = spv::OpIAddCarry;
4742 typeId = builder.makeStructResultType(typeId0, typeId0);
4743 consumedOperands = 2;
4744 break;
4745 case glslang::EOpSubBorrow:
4746 opCode = spv::OpISubBorrow;
4747 typeId = builder.makeStructResultType(typeId0, typeId0);
4748 consumedOperands = 2;
4749 break;
4750 case glslang::EOpUMulExtended:
4751 opCode = spv::OpUMulExtended;
4752 typeId = builder.makeStructResultType(typeId0, typeId0);
4753 consumedOperands = 2;
4754 break;
4755 case glslang::EOpIMulExtended:
4756 opCode = spv::OpSMulExtended;
4757 typeId = builder.makeStructResultType(typeId0, typeId0);
4758 consumedOperands = 2;
4759 break;
4760 case glslang::EOpBitfieldExtract:
4761 if (isUnsigned)
4762 opCode = spv::OpBitFieldUExtract;
4763 else
4764 opCode = spv::OpBitFieldSExtract;
4765 break;
4766 case glslang::EOpBitfieldInsert:
4767 opCode = spv::OpBitFieldInsert;
4768 break;
4769
4770 case glslang::EOpFma:
4771 libCall = spv::GLSLstd450Fma;
4772 break;
4773 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004774 {
4775 libCall = spv::GLSLstd450FrexpStruct;
4776 assert(builder.isPointerType(typeId1));
4777 typeId1 = builder.getContainedTypeId(typeId1);
4778#ifdef AMD_EXTENSIONS
4779 int width = builder.getScalarTypeWidth(typeId1);
4780#else
4781 int width = 32;
4782#endif
4783 if (builder.getNumComponents(operands[0]) == 1)
4784 frexpIntType = builder.makeIntegerType(width, true);
4785 else
4786 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
4787 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4788 consumedOperands = 1;
4789 }
John Kessenich55e7d112015-11-15 21:33:39 -07004790 break;
4791 case glslang::EOpLdexp:
4792 libCall = spv::GLSLstd450Ldexp;
4793 break;
4794
Rex Xu574ab042016-04-14 16:53:07 +08004795 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004796 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004797
Rex Xu9d93a232016-05-05 12:30:44 +08004798#ifdef AMD_EXTENSIONS
4799 case glslang::EOpSwizzleInvocations:
4800 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4801 libCall = spv::SwizzleInvocationsAMD;
4802 break;
4803 case glslang::EOpSwizzleInvocationsMasked:
4804 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4805 libCall = spv::SwizzleInvocationsMaskedAMD;
4806 break;
4807 case glslang::EOpWriteInvocation:
4808 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4809 libCall = spv::WriteInvocationAMD;
4810 break;
4811
4812 case glslang::EOpMin3:
4813 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4814 if (isFloat)
4815 libCall = spv::FMin3AMD;
4816 else {
4817 if (isUnsigned)
4818 libCall = spv::UMin3AMD;
4819 else
4820 libCall = spv::SMin3AMD;
4821 }
4822 break;
4823 case glslang::EOpMax3:
4824 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4825 if (isFloat)
4826 libCall = spv::FMax3AMD;
4827 else {
4828 if (isUnsigned)
4829 libCall = spv::UMax3AMD;
4830 else
4831 libCall = spv::SMax3AMD;
4832 }
4833 break;
4834 case glslang::EOpMid3:
4835 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4836 if (isFloat)
4837 libCall = spv::FMid3AMD;
4838 else {
4839 if (isUnsigned)
4840 libCall = spv::UMid3AMD;
4841 else
4842 libCall = spv::SMid3AMD;
4843 }
4844 break;
4845
4846 case glslang::EOpInterpolateAtVertex:
4847 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4848 libCall = spv::InterpolateAtVertexAMD;
4849 break;
4850#endif
4851
John Kessenich140f3df2015-06-26 16:58:36 -06004852 default:
4853 return 0;
4854 }
4855
4856 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004857 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004858 // Use an extended instruction from the standard library.
4859 // Construct the call arguments, without modifying the original operands vector.
4860 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4861 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004862 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004863 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004864 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004865 case 0:
4866 // should all be handled by visitAggregate and createNoArgOperation
4867 assert(0);
4868 return 0;
4869 case 1:
4870 // should all be handled by createUnaryOperation
4871 assert(0);
4872 return 0;
4873 case 2:
4874 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4875 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004876 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004877 // anything 3 or over doesn't have l-value operands, so all should be consumed
4878 assert(consumedOperands == operands.size());
4879 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004880 break;
4881 }
4882 }
4883
John Kessenich55e7d112015-11-15 21:33:39 -07004884 // Decode the return types that were structures
4885 switch (op) {
4886 case glslang::EOpAddCarry:
4887 case glslang::EOpSubBorrow:
4888 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4889 id = builder.createCompositeExtract(id, typeId0, 0);
4890 break;
4891 case glslang::EOpUMulExtended:
4892 case glslang::EOpIMulExtended:
4893 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4894 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4895 break;
4896 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004897 {
4898 assert(operands.size() == 2);
4899 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
4900 // "exp" is floating-point type (from HLSL intrinsic)
4901 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
4902 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
4903 builder.createStore(member1, operands[1]);
4904 } else
4905 // "exp" is integer type (from GLSL built-in function)
4906 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4907 id = builder.createCompositeExtract(id, typeId0, 0);
4908 }
John Kessenich55e7d112015-11-15 21:33:39 -07004909 break;
4910 default:
4911 break;
4912 }
4913
John Kessenich32cfd492016-02-02 12:37:46 -07004914 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004915}
4916
Rex Xu9d93a232016-05-05 12:30:44 +08004917// Intrinsics with no arguments (or no return value, and no precision).
4918spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004919{
4920 // TODO: get the barrier operands correct
4921
4922 switch (op) {
4923 case glslang::EOpEmitVertex:
4924 builder.createNoResultOp(spv::OpEmitVertex);
4925 return 0;
4926 case glslang::EOpEndPrimitive:
4927 builder.createNoResultOp(spv::OpEndPrimitive);
4928 return 0;
4929 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004930 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004931 return 0;
4932 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004933 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004934 return 0;
4935 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004936 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004937 return 0;
4938 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004939 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004940 return 0;
4941 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004942 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004943 return 0;
4944 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004945 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004946 return 0;
4947 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004948 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004949 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004950 case glslang::EOpAllMemoryBarrierWithGroupSync:
4951 // Control barrier with non-"None" semantic is also a memory barrier.
4952 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4953 return 0;
4954 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4955 // Control barrier with non-"None" semantic is also a memory barrier.
4956 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4957 return 0;
4958 case glslang::EOpWorkgroupMemoryBarrier:
4959 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4960 return 0;
4961 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4962 // Control barrier with non-"None" semantic is also a memory barrier.
4963 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4964 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004965#ifdef AMD_EXTENSIONS
4966 case glslang::EOpTime:
4967 {
4968 std::vector<spv::Id> args; // Dummy arguments
4969 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4970 return builder.setPrecision(id, precision);
4971 }
4972#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004973 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004974 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004975 return 0;
4976 }
4977}
4978
4979spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4980{
John Kessenich2f273362015-07-18 22:34:27 -06004981 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004982 spv::Id id;
4983 if (symbolValues.end() != iter) {
4984 id = iter->second;
4985 return id;
4986 }
4987
4988 // it was not found, create it
4989 id = createSpvVariable(symbol);
4990 symbolValues[symbol->getId()] = id;
4991
Rex Xuc884b4a2016-06-29 15:03:44 +08004992 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004993 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004994 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004995 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004996 if (symbol->getType().getQualifier().hasSpecConstantId())
4997 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004998 if (symbol->getQualifier().hasIndex())
4999 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5000 if (symbol->getQualifier().hasComponent())
5001 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5002 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005003 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005004 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005005 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005006 if (symbol->getQualifier().hasXfbBuffer())
5007 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5008 if (symbol->getQualifier().hasXfbOffset())
5009 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5010 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005011 // atomic counters use this:
5012 if (symbol->getQualifier().hasOffset())
5013 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005014 }
5015
scygan2c864272016-05-18 18:09:17 +02005016 if (symbol->getQualifier().hasLocation())
5017 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005018 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005019 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005020 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005021 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005022 }
John Kessenich140f3df2015-06-26 16:58:36 -06005023 if (symbol->getQualifier().hasSet())
5024 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005025 else if (IsDescriptorResource(symbol->getType())) {
5026 // default to 0
5027 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5028 }
John Kessenich140f3df2015-06-26 16:58:36 -06005029 if (symbol->getQualifier().hasBinding())
5030 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005031 if (symbol->getQualifier().hasAttachment())
5032 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005033 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005034 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005035 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005036 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005037 if (symbol->getQualifier().hasXfbBuffer())
5038 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5039 }
5040
Rex Xu1da878f2016-02-21 20:59:01 +08005041 if (symbol->getType().isImage()) {
5042 std::vector<spv::Decoration> memory;
5043 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5044 for (unsigned int i = 0; i < memory.size(); ++i)
5045 addDecoration(id, memory[i]);
5046 }
5047
John Kessenich140f3df2015-06-26 16:58:36 -06005048 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005049 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005050 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005051 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005052
John Kessenichecba76f2017-01-06 00:34:48 -07005053#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005054 if (builtIn == spv::BuiltInSampleMask) {
5055 spv::Decoration decoration;
5056 // GL_NV_sample_mask_override_coverage extension
5057 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005058 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005059 else
5060 decoration = (spv::Decoration)spv::DecorationMax;
5061 addDecoration(id, decoration);
5062 if (decoration != spv::DecorationMax) {
5063 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5064 }
5065 }
chaoc771d89f2017-01-13 01:10:53 -08005066 else if (builtIn == spv::BuiltInLayer) {
5067 // SPV_NV_viewport_array2 extension
5068 if (symbol->getQualifier().layoutViewportRelative)
5069 {
5070 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5071 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5072 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5073 }
5074 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5075 {
5076 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5077 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5078 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5079 }
5080 }
5081
chaoc6e5acae2016-12-20 13:28:52 -08005082 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005083 addDecoration(id, spv::DecorationPassthroughNV);
5084 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005085 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5086 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005087#endif
5088
John Kessenich140f3df2015-06-26 16:58:36 -06005089 return id;
5090}
5091
John Kessenich55e7d112015-11-15 21:33:39 -07005092// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005093void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5094{
John Kessenich4016e382016-07-15 11:53:56 -06005095 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005096 builder.addDecoration(id, dec);
5097}
5098
John Kessenich55e7d112015-11-15 21:33:39 -07005099// If 'dec' is valid, add a one-operand decoration to an object
5100void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5101{
John Kessenich4016e382016-07-15 11:53:56 -06005102 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005103 builder.addDecoration(id, dec, value);
5104}
5105
5106// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005107void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5108{
John Kessenich4016e382016-07-15 11:53:56 -06005109 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005110 builder.addMemberDecoration(id, (unsigned)member, dec);
5111}
5112
John Kessenich92187592016-02-01 13:45:25 -07005113// If 'dec' is valid, add a one-operand decoration to a struct member
5114void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5115{
John Kessenich4016e382016-07-15 11:53:56 -06005116 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005117 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5118}
5119
John Kessenich55e7d112015-11-15 21:33:39 -07005120// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005121// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005122//
5123// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5124//
5125// Recursively walk the nodes. The nodes form a tree whose leaves are
5126// regular constants, which themselves are trees that createSpvConstant()
5127// recursively walks. So, this function walks the "top" of the tree:
5128// - emit specialization constant-building instructions for specConstant
5129// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005130spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005131{
John Kessenich7cc0e282016-03-20 00:46:02 -06005132 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005133
qining4f4bb812016-04-03 23:55:17 -04005134 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005135 if (! node.getQualifier().specConstant) {
5136 // hand off to the non-spec-constant path
5137 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5138 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005139 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005140 nextConst, false);
5141 }
5142
5143 // We now know we have a specialization constant to build
5144
John Kessenichd94c0032016-05-30 19:29:40 -06005145 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005146 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5147 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5148 std::vector<spv::Id> dimConstId;
5149 for (int dim = 0; dim < 3; ++dim) {
5150 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5151 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5152 if (specConst)
5153 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5154 }
5155 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5156 }
5157
5158 // An AST node labelled as specialization constant should be a symbol node.
5159 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5160 if (auto* sn = node.getAsSymbolNode()) {
5161 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005162 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5163 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5164 // will set the builder into spec constant op instruction generating mode.
5165 sub_tree->traverse(this);
5166 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005167 } else if (auto* const_union_array = &sn->getConstArray()){
5168 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005169 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5170 builder.addName(id, sn->getName().c_str());
5171 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005172 }
5173 }
qining4f4bb812016-04-03 23:55:17 -04005174
5175 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5176 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005177 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005178 exit(1);
5179 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005180}
5181
John Kessenich140f3df2015-06-26 16:58:36 -06005182// Use 'consts' as the flattened glslang source of scalar constants to recursively
5183// build the aggregate SPIR-V constant.
5184//
5185// If there are not enough elements present in 'consts', 0 will be substituted;
5186// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5187//
qining08408382016-03-21 09:51:37 -04005188spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005189{
5190 // vector of constants for SPIR-V
5191 std::vector<spv::Id> spvConsts;
5192
5193 // Type is used for struct and array constants
5194 spv::Id typeId = convertGlslangToSpvType(glslangType);
5195
5196 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005197 glslang::TType elementType(glslangType, 0);
5198 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005199 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005200 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005201 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005202 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005203 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005204 } else if (glslangType.getStruct()) {
5205 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5206 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005207 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005208 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005209 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5210 bool zero = nextConst >= consts.size();
5211 switch (glslangType.getBasicType()) {
5212 case glslang::EbtInt:
5213 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5214 break;
5215 case glslang::EbtUint:
5216 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5217 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005218 case glslang::EbtInt64:
5219 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5220 break;
5221 case glslang::EbtUint64:
5222 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5223 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005224 case glslang::EbtFloat:
5225 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5226 break;
5227 case glslang::EbtDouble:
5228 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5229 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005230#ifdef AMD_EXTENSIONS
5231 case glslang::EbtFloat16:
5232 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5233 break;
5234#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005235 case glslang::EbtBool:
5236 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5237 break;
5238 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005239 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005240 break;
5241 }
5242 ++nextConst;
5243 }
5244 } else {
5245 // we have a non-aggregate (scalar) constant
5246 bool zero = nextConst >= consts.size();
5247 spv::Id scalar = 0;
5248 switch (glslangType.getBasicType()) {
5249 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005250 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005251 break;
5252 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005253 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005254 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005255 case glslang::EbtInt64:
5256 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5257 break;
5258 case glslang::EbtUint64:
5259 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5260 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005261 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005262 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005263 break;
5264 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005265 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005266 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005267#ifdef AMD_EXTENSIONS
5268 case glslang::EbtFloat16:
5269 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5270 break;
5271#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005272 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005273 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005274 break;
5275 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005276 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005277 break;
5278 }
5279 ++nextConst;
5280 return scalar;
5281 }
5282
5283 return builder.makeCompositeConstant(typeId, spvConsts);
5284}
5285
John Kessenich7c1aa102015-10-15 13:29:11 -06005286// Return true if the node is a constant or symbol whose reading has no
5287// non-trivial observable cost or effect.
5288bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5289{
5290 // don't know what this is
5291 if (node == nullptr)
5292 return false;
5293
5294 // a constant is safe
5295 if (node->getAsConstantUnion() != nullptr)
5296 return true;
5297
5298 // not a symbol means non-trivial
5299 if (node->getAsSymbolNode() == nullptr)
5300 return false;
5301
5302 // a symbol, depends on what's being read
5303 switch (node->getType().getQualifier().storage) {
5304 case glslang::EvqTemporary:
5305 case glslang::EvqGlobal:
5306 case glslang::EvqIn:
5307 case glslang::EvqInOut:
5308 case glslang::EvqConst:
5309 case glslang::EvqConstReadOnly:
5310 case glslang::EvqUniform:
5311 return true;
5312 default:
5313 return false;
5314 }
qining25262b32016-05-06 17:25:16 -04005315}
John Kessenich7c1aa102015-10-15 13:29:11 -06005316
5317// A node is trivial if it is a single operation with no side effects.
5318// Error on the side of saying non-trivial.
5319// Return true if trivial.
5320bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5321{
5322 if (node == nullptr)
5323 return false;
5324
5325 // symbols and constants are trivial
5326 if (isTrivialLeaf(node))
5327 return true;
5328
5329 // otherwise, it needs to be a simple operation or one or two leaf nodes
5330
5331 // not a simple operation
5332 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5333 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5334 if (binaryNode == nullptr && unaryNode == nullptr)
5335 return false;
5336
5337 // not on leaf nodes
5338 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5339 return false;
5340
5341 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5342 return false;
5343 }
5344
5345 switch (node->getAsOperator()->getOp()) {
5346 case glslang::EOpLogicalNot:
5347 case glslang::EOpConvIntToBool:
5348 case glslang::EOpConvUintToBool:
5349 case glslang::EOpConvFloatToBool:
5350 case glslang::EOpConvDoubleToBool:
5351 case glslang::EOpEqual:
5352 case glslang::EOpNotEqual:
5353 case glslang::EOpLessThan:
5354 case glslang::EOpGreaterThan:
5355 case glslang::EOpLessThanEqual:
5356 case glslang::EOpGreaterThanEqual:
5357 case glslang::EOpIndexDirect:
5358 case glslang::EOpIndexDirectStruct:
5359 case glslang::EOpLogicalXor:
5360 case glslang::EOpAny:
5361 case glslang::EOpAll:
5362 return true;
5363 default:
5364 return false;
5365 }
5366}
5367
5368// Emit short-circuiting code, where 'right' is never evaluated unless
5369// the left side is true (for &&) or false (for ||).
5370spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5371{
5372 spv::Id boolTypeId = builder.makeBoolType();
5373
5374 // emit left operand
5375 builder.clearAccessChain();
5376 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005377 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005378
5379 // Operands to accumulate OpPhi operands
5380 std::vector<spv::Id> phiOperands;
5381 // accumulate left operand's phi information
5382 phiOperands.push_back(leftId);
5383 phiOperands.push_back(builder.getBuildPoint()->getId());
5384
5385 // Make the two kinds of operation symmetric with a "!"
5386 // || => emit "if (! left) result = right"
5387 // && => emit "if ( left) result = right"
5388 //
5389 // TODO: this runtime "not" for || could be avoided by adding functionality
5390 // to 'builder' to have an "else" without an "then"
5391 if (op == glslang::EOpLogicalOr)
5392 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5393
5394 // make an "if" based on the left value
5395 spv::Builder::If ifBuilder(leftId, builder);
5396
5397 // emit right operand as the "then" part of the "if"
5398 builder.clearAccessChain();
5399 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005400 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005401
5402 // accumulate left operand's phi information
5403 phiOperands.push_back(rightId);
5404 phiOperands.push_back(builder.getBuildPoint()->getId());
5405
5406 // finish the "if"
5407 ifBuilder.makeEndIf();
5408
5409 // phi together the two results
5410 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5411}
5412
Rex Xu9d93a232016-05-05 12:30:44 +08005413// Return type Id of the imported set of extended instructions corresponds to the name.
5414// Import this set if it has not been imported yet.
5415spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5416{
5417 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5418 return extBuiltinMap[name];
5419 else {
Rex Xu51596642016-09-21 18:56:12 +08005420 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005421 spv::Id extBuiltins = builder.import(name);
5422 extBuiltinMap[name] = extBuiltins;
5423 return extBuiltins;
5424 }
5425}
5426
John Kessenich140f3df2015-06-26 16:58:36 -06005427}; // end anonymous namespace
5428
5429namespace glslang {
5430
John Kessenich68d78fd2015-07-12 19:28:10 -06005431void GetSpirvVersion(std::string& version)
5432{
John Kessenich9e55f632015-07-15 10:03:39 -06005433 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005434 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005435 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005436 version = buf;
5437}
5438
John Kessenich140f3df2015-06-26 16:58:36 -06005439// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005440void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005441{
5442 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005443 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005444 if (out.fail())
5445 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005446 for (int i = 0; i < (int)spirv.size(); ++i) {
5447 unsigned int word = spirv[i];
5448 out.write((const char*)&word, 4);
5449 }
5450 out.close();
5451}
5452
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005453// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005454void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005455{
5456 std::ofstream out;
5457 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005458 if (out.fail())
5459 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005460 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005461 if (varName != nullptr) {
5462 out << "\t #pragma once" << std::endl;
5463 out << "const uint32_t " << varName << "[] = {" << std::endl;
5464 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005465 const int WORDS_PER_LINE = 8;
5466 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5467 out << "\t";
5468 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5469 const unsigned int word = spirv[i + j];
5470 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5471 if (i + j + 1 < (int)spirv.size()) {
5472 out << ",";
5473 }
5474 }
5475 out << std::endl;
5476 }
Flavio15017db2017-02-15 14:29:33 -08005477 if (varName != nullptr) {
5478 out << "};";
5479 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005480 out.close();
5481}
5482
John Kessenich140f3df2015-06-26 16:58:36 -06005483//
5484// Set up the glslang traversal
5485//
5486void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5487{
Lei Zhang17535f72016-05-04 15:55:59 -04005488 spv::SpvBuildLogger logger;
5489 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005490}
5491
Lei Zhang17535f72016-05-04 15:55:59 -04005492void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005493{
John Kessenich140f3df2015-06-26 16:58:36 -06005494 TIntermNode* root = intermediate.getTreeRoot();
5495
5496 if (root == 0)
5497 return;
5498
5499 glslang::GetThreadPoolAllocator().push();
5500
Lei Zhang17535f72016-05-04 15:55:59 -04005501 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005502 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005503 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005504 it.dumpSpv(spirv);
5505
5506 glslang::GetThreadPoolAllocator().pop();
5507}
5508
5509}; // end namespace glslang