blob: 6dee3bf3d5b06129539e4628ff197601f8b40713 [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 Kessenich927608b2017-01-06 12:34:14 -0700225 // Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
Dan Baker55d5f2d2016-08-15 16:05:45 -0400226 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600227 default:
228 return spv::SourceLanguageUnknown;
229 }
230}
231
232// Translate glslang language (stage) to SPIR-V execution model.
233spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
234{
235 switch (stage) {
236 case EShLangVertex: return spv::ExecutionModelVertex;
237 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
238 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
239 case EShLangGeometry: return spv::ExecutionModelGeometry;
240 case EShLangFragment: return spv::ExecutionModelFragment;
241 case EShLangCompute: return spv::ExecutionModelGLCompute;
242 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700243 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600244 return spv::ExecutionModelFragment;
245 }
246}
247
248// Translate glslang type to SPIR-V storage class.
249spv::StorageClass TranslateStorageClass(const glslang::TType& type)
250{
251 if (type.getQualifier().isPipeInput())
252 return spv::StorageClassInput;
253 else if (type.getQualifier().isPipeOutput())
254 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700255 else if (type.getBasicType() == glslang::EbtAtomicUint)
256 return spv::StorageClassAtomicCounter;
John Kessenich4a57dce2017-02-24 19:15:46 -0700257 else if (type.containsOpaque())
258 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600259 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700260 if (type.getQualifier().layoutPushConstant)
261 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600262 if (type.getBasicType() == glslang::EbtBlock)
263 return spv::StorageClassUniform;
264 else
265 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600266 } else {
267 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700268 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
269 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600270 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
271 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400272 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700273 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600274 return spv::StorageClassFunction;
275 }
276 }
277}
278
279// Translate glslang sampler type to SPIR-V dimensionality.
280spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
281{
282 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700283 case glslang::Esd1D: return spv::Dim1D;
284 case glslang::Esd2D: return spv::Dim2D;
285 case glslang::Esd3D: return spv::Dim3D;
286 case glslang::EsdCube: return spv::DimCube;
287 case glslang::EsdRect: return spv::DimRect;
288 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700289 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600290 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700291 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600292 return spv::Dim2D;
293 }
294}
295
John Kessenichf6640762016-08-01 19:44:00 -0600296// Translate glslang precision to SPIR-V precision decorations.
297spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600298{
John Kessenichf6640762016-08-01 19:44:00 -0600299 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700300 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600301 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600302 default:
303 return spv::NoPrecision;
304 }
305}
306
John Kessenichf6640762016-08-01 19:44:00 -0600307// Translate glslang type to SPIR-V precision decorations.
308spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
309{
310 return TranslatePrecisionDecoration(type.getQualifier().precision);
311}
312
John Kessenich140f3df2015-06-26 16:58:36 -0600313// Translate glslang type to SPIR-V block decorations.
314spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
315{
316 if (type.getBasicType() == glslang::EbtBlock) {
317 switch (type.getQualifier().storage) {
318 case glslang::EvqUniform: return spv::DecorationBlock;
319 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
320 case glslang::EvqVaryingIn: return spv::DecorationBlock;
321 case glslang::EvqVaryingOut: return spv::DecorationBlock;
322 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700323 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600324 break;
325 }
326 }
327
John Kessenich4016e382016-07-15 11:53:56 -0600328 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600329}
330
Rex Xu1da878f2016-02-21 20:59:01 +0800331// Translate glslang type to SPIR-V memory decorations.
332void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
333{
334 if (qualifier.coherent)
335 memory.push_back(spv::DecorationCoherent);
336 if (qualifier.volatil)
337 memory.push_back(spv::DecorationVolatile);
338 if (qualifier.restrict)
339 memory.push_back(spv::DecorationRestrict);
340 if (qualifier.readonly)
341 memory.push_back(spv::DecorationNonWritable);
342 if (qualifier.writeonly)
343 memory.push_back(spv::DecorationNonReadable);
344}
345
John Kessenich140f3df2015-06-26 16:58:36 -0600346// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700347spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600348{
349 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700350 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600351 case glslang::ElmRowMajor:
352 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700353 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600354 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700355 default:
356 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600357 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600358 }
359 } else {
360 switch (type.getBasicType()) {
361 default:
John Kessenich4016e382016-07-15 11:53:56 -0600362 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600363 break;
364 case glslang::EbtBlock:
365 switch (type.getQualifier().storage) {
366 case glslang::EvqUniform:
367 case glslang::EvqBuffer:
368 switch (type.getQualifier().layoutPacking) {
369 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600370 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
371 default:
John Kessenich4016e382016-07-15 11:53:56 -0600372 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600373 }
374 case glslang::EvqVaryingIn:
375 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700376 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600378 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700379 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600380 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600381 }
382 }
383 }
384}
385
386// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600387// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700388// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800389spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600390{
Rex Xubbceed72016-05-21 09:40:44 +0800391 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700392 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600393 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800394 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700395 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700396 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600397 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800398#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800399 else if (qualifier.explicitInterp) {
400 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800401 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800402 }
Rex Xu9d93a232016-05-05 12:30:44 +0800403#endif
Rex Xubbceed72016-05-21 09:40:44 +0800404 else
John Kessenich4016e382016-07-15 11:53:56 -0600405 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800406}
407
408// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600409// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800410// should be applied.
411spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
412{
413 if (qualifier.patch)
414 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700415 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600416 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700417 else if (qualifier.sample) {
418 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600419 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700420 } else
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600422}
423
John Kessenich92187592016-02-01 13:45:25 -0700424// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700425spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600426{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700427 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600428 return spv::DecorationInvariant;
429 else
John Kessenich4016e382016-07-15 11:53:56 -0600430 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600431}
432
qining9220dbb2016-05-04 17:34:38 -0400433// If glslang type is noContraction, return SPIR-V NoContraction decoration.
434spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
435{
436 if (qualifier.noContraction)
437 return spv::DecorationNoContraction;
438 else
John Kessenich4016e382016-07-15 11:53:56 -0600439 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400440}
441
David Netoa901ffe2016-06-08 14:11:40 +0100442// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
443// associated capabilities when required. For some built-in variables, a capability
444// is generated only when using the variable in an executable instruction, but not when
445// just declaring a struct member variable with it. This is true for PointSize,
446// ClipDistance, and CullDistance.
447spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600448{
449 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700450 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600451 // Defer adding the capability until the built-in is actually used.
452 if (! memberDeclaration) {
453 switch (glslangIntermediate->getStage()) {
454 case EShLangGeometry:
455 builder.addCapability(spv::CapabilityGeometryPointSize);
456 break;
457 case EShLangTessControl:
458 case EShLangTessEvaluation:
459 builder.addCapability(spv::CapabilityTessellationPointSize);
460 break;
461 default:
462 break;
463 }
John Kessenich92187592016-02-01 13:45:25 -0700464 }
465 return spv::BuiltInPointSize;
466
John Kessenichebb50532016-05-16 19:22:05 -0600467 // These *Distance capabilities logically belong here, but if the member is declared and
468 // then never used, consumers of SPIR-V prefer the capability not be declared.
469 // They are now generated when used, rather than here when declared.
470 // Potentially, the specification should be more clear what the minimum
471 // use needed is to trigger the capability.
472 //
John Kessenich92187592016-02-01 13:45:25 -0700473 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100474 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800475 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700476 return spv::BuiltInClipDistance;
477
478 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100479 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800480 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700481 return spv::BuiltInCullDistance;
482
483 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800484 if (!memberDeclaration) {
485 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800486#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800487 if (glslangIntermediate->getStage() == EShLangVertex ||
488 glslangIntermediate->getStage() == EShLangTessControl ||
489 glslangIntermediate->getStage() == EShLangTessEvaluation) {
490
491 builder.addExtension(spv::E_SPV_NV_viewport_array2);
492 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
493 }
chaoc771d89f2017-01-13 01:10:53 -0800494#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800495 }
John Kessenich92187592016-02-01 13:45:25 -0700496 return spv::BuiltInViewportIndex;
497
John Kessenich5e801132016-02-15 11:09:46 -0700498 case glslang::EbvSampleId:
499 builder.addCapability(spv::CapabilitySampleRateShading);
500 return spv::BuiltInSampleId;
501
502 case glslang::EbvSamplePosition:
503 builder.addCapability(spv::CapabilitySampleRateShading);
504 return spv::BuiltInSamplePosition;
505
506 case glslang::EbvSampleMask:
507 builder.addCapability(spv::CapabilitySampleRateShading);
508 return spv::BuiltInSampleMask;
509
John Kessenich78a45572016-07-08 14:05:15 -0600510 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800511 if (!memberDeclaration) {
512 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800513#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800514 if (glslangIntermediate->getStage() == EShLangVertex ||
515 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800516 glslangIntermediate->getStage() == EShLangTessEvaluation) {
517
chaoc771d89f2017-01-13 01:10:53 -0800518 builder.addExtension(spv::E_SPV_NV_viewport_array2);
519 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
520 }
chaoc771d89f2017-01-13 01:10:53 -0800521#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800522 }
523
John Kessenich78a45572016-07-08 14:05:15 -0600524 return spv::BuiltInLayer;
525
John Kessenich140f3df2015-06-26 16:58:36 -0600526 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600527 case glslang::EbvVertexId: return spv::BuiltInVertexId;
528 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700529 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
530 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800531
John Kessenichda581a22015-10-14 14:10:30 -0600532 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800533 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
534 builder.addCapability(spv::CapabilityDrawParameters);
535 return spv::BuiltInBaseVertex;
536
John Kessenichda581a22015-10-14 14:10:30 -0600537 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800538 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
539 builder.addCapability(spv::CapabilityDrawParameters);
540 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200541
John Kessenichda581a22015-10-14 14:10:30 -0600542 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800543 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
544 builder.addCapability(spv::CapabilityDrawParameters);
545 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200546
547 case glslang::EbvPrimitiveId:
548 if (glslangIntermediate->getStage() == EShLangFragment)
549 builder.addCapability(spv::CapabilityGeometry);
550 return spv::BuiltInPrimitiveId;
551
John Kessenich140f3df2015-06-26 16:58:36 -0600552 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600553 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
554 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
555 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
556 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
557 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
558 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
559 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600560 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
561 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
562 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
563 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
564 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
565 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
566 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
567 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800568
Rex Xu574ab042016-04-14 16:53:07 +0800569 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800570 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800571 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
572 return spv::BuiltInSubgroupSize;
573
Rex Xu574ab042016-04-14 16:53:07 +0800574 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800575 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800576 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
577 return spv::BuiltInSubgroupLocalInvocationId;
578
Rex Xu574ab042016-04-14 16:53:07 +0800579 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800580 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
581 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
582 return spv::BuiltInSubgroupEqMaskKHR;
583
Rex Xu574ab042016-04-14 16:53:07 +0800584 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800585 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
586 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
587 return spv::BuiltInSubgroupGeMaskKHR;
588
Rex Xu574ab042016-04-14 16:53:07 +0800589 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800590 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
591 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
592 return spv::BuiltInSubgroupGtMaskKHR;
593
Rex Xu574ab042016-04-14 16:53:07 +0800594 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800595 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
596 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
597 return spv::BuiltInSubgroupLeMaskKHR;
598
Rex Xu574ab042016-04-14 16:53:07 +0800599 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800600 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
601 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
602 return spv::BuiltInSubgroupLtMaskKHR;
603
Rex Xu9d93a232016-05-05 12:30:44 +0800604#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800605 case glslang::EbvBaryCoordNoPersp:
606 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
607 return spv::BuiltInBaryCoordNoPerspAMD;
608
609 case glslang::EbvBaryCoordNoPerspCentroid:
610 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
611 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
612
613 case glslang::EbvBaryCoordNoPerspSample:
614 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
615 return spv::BuiltInBaryCoordNoPerspSampleAMD;
616
617 case glslang::EbvBaryCoordSmooth:
618 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
619 return spv::BuiltInBaryCoordSmoothAMD;
620
621 case glslang::EbvBaryCoordSmoothCentroid:
622 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
623 return spv::BuiltInBaryCoordSmoothCentroidAMD;
624
625 case glslang::EbvBaryCoordSmoothSample:
626 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
627 return spv::BuiltInBaryCoordSmoothSampleAMD;
628
629 case glslang::EbvBaryCoordPullModel:
630 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
631 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800632#endif
chaoc771d89f2017-01-13 01:10:53 -0800633
John Kessenich6c8aaac2017-02-27 01:20:51 -0700634 case glslang::EbvDeviceIndex:
635 builder.addExtension(spv::E_SPV_KHR_device_group);
636 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700637 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700638
639 case glslang::EbvViewIndex:
640 builder.addExtension(spv::E_SPV_KHR_multiview);
641 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700642 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700643
chaoc771d89f2017-01-13 01:10:53 -0800644#ifdef NV_EXTENSIONS
645 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800646 if (!memberDeclaration) {
647 builder.addExtension(spv::E_SPV_NV_viewport_array2);
648 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
649 }
chaoc771d89f2017-01-13 01:10:53 -0800650 return spv::BuiltInViewportMaskNV;
651 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800652 if (!memberDeclaration) {
653 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
654 builder.addCapability(spv::CapabilityShaderStereoViewNV);
655 }
chaoc771d89f2017-01-13 01:10:53 -0800656 return spv::BuiltInSecondaryPositionNV;
657 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800658 if (!memberDeclaration) {
659 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
660 builder.addCapability(spv::CapabilityShaderStereoViewNV);
661 }
chaoc771d89f2017-01-13 01:10:53 -0800662 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800663 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800664 if (!memberDeclaration) {
665 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
666 builder.addCapability(spv::CapabilityPerViewAttributesNV);
667 }
chaocdf3956c2017-02-14 14:52:34 -0800668 return spv::BuiltInPositionPerViewNV;
669 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800670 if (!memberDeclaration) {
671 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
672 builder.addCapability(spv::CapabilityPerViewAttributesNV);
673 }
chaocdf3956c2017-02-14 14:52:34 -0800674 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800675#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800676 default:
677 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600678 }
679}
680
Rex Xufc618912015-09-09 16:42:49 +0800681// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700682spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800683{
684 assert(type.getBasicType() == glslang::EbtSampler);
685
John Kessenich5d0fa972016-02-15 11:57:00 -0700686 // Check for capabilities
687 switch (type.getQualifier().layoutFormat) {
688 case glslang::ElfRg32f:
689 case glslang::ElfRg16f:
690 case glslang::ElfR11fG11fB10f:
691 case glslang::ElfR16f:
692 case glslang::ElfRgba16:
693 case glslang::ElfRgb10A2:
694 case glslang::ElfRg16:
695 case glslang::ElfRg8:
696 case glslang::ElfR16:
697 case glslang::ElfR8:
698 case glslang::ElfRgba16Snorm:
699 case glslang::ElfRg16Snorm:
700 case glslang::ElfRg8Snorm:
701 case glslang::ElfR16Snorm:
702 case glslang::ElfR8Snorm:
703
704 case glslang::ElfRg32i:
705 case glslang::ElfRg16i:
706 case glslang::ElfRg8i:
707 case glslang::ElfR16i:
708 case glslang::ElfR8i:
709
710 case glslang::ElfRgb10a2ui:
711 case glslang::ElfRg32ui:
712 case glslang::ElfRg16ui:
713 case glslang::ElfRg8ui:
714 case glslang::ElfR16ui:
715 case glslang::ElfR8ui:
716 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
717 break;
718
719 default:
720 break;
721 }
722
723 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800724 switch (type.getQualifier().layoutFormat) {
725 case glslang::ElfNone: return spv::ImageFormatUnknown;
726 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
727 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
728 case glslang::ElfR32f: return spv::ImageFormatR32f;
729 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
730 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
731 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
732 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
733 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
734 case glslang::ElfR16f: return spv::ImageFormatR16f;
735 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
736 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
737 case glslang::ElfRg16: return spv::ImageFormatRg16;
738 case glslang::ElfRg8: return spv::ImageFormatRg8;
739 case glslang::ElfR16: return spv::ImageFormatR16;
740 case glslang::ElfR8: return spv::ImageFormatR8;
741 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
742 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
743 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
744 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
745 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
746 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
747 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
748 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
749 case glslang::ElfR32i: return spv::ImageFormatR32i;
750 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
751 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
752 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
753 case glslang::ElfR16i: return spv::ImageFormatR16i;
754 case glslang::ElfR8i: return spv::ImageFormatR8i;
755 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
756 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
757 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
758 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
759 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
760 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
761 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
762 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
763 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
764 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600765 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800766 }
767}
768
qining25262b32016-05-06 17:25:16 -0400769// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700770// descriptor set.
771bool IsDescriptorResource(const glslang::TType& type)
772{
John Kessenichf7497e22016-03-08 21:36:22 -0700773 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700774 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700775 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700776
777 // non block...
778 // basically samplerXXX/subpass/sampler/texture are all included
779 // if they are the global-scope-class, not the function parameter
780 // (or local, if they ever exist) class.
781 if (type.getBasicType() == glslang::EbtSampler)
782 return type.getQualifier().isUniformOrBuffer();
783
784 // None of the above.
785 return false;
786}
787
John Kesseniche0b6cad2015-12-24 10:30:13 -0700788void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
789{
790 if (child.layoutMatrix == glslang::ElmNone)
791 child.layoutMatrix = parent.layoutMatrix;
792
793 if (parent.invariant)
794 child.invariant = true;
795 if (parent.nopersp)
796 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800797#ifdef AMD_EXTENSIONS
798 if (parent.explicitInterp)
799 child.explicitInterp = true;
800#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700801 if (parent.flat)
802 child.flat = true;
803 if (parent.centroid)
804 child.centroid = true;
805 if (parent.patch)
806 child.patch = true;
807 if (parent.sample)
808 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800809 if (parent.coherent)
810 child.coherent = true;
811 if (parent.volatil)
812 child.volatil = true;
813 if (parent.restrict)
814 child.restrict = true;
815 if (parent.readonly)
816 child.readonly = true;
817 if (parent.writeonly)
818 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700819}
820
John Kessenichf2b7f332016-09-01 17:05:23 -0600821bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700822{
John Kessenich7b9fa252016-01-21 18:56:57 -0700823 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600824 // - struct members might inherit from a struct declaration
825 // (note that non-block structs don't explicitly inherit,
826 // only implicitly, meaning no decoration involved)
827 // - affect decorations on the struct members
828 // (note smooth does not, and expecting something like volatile
829 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700830 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600831 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700832}
833
John Kessenich140f3df2015-06-26 16:58:36 -0600834//
835// Implement the TGlslangToSpvTraverser class.
836//
837
Lei Zhang17535f72016-05-04 15:55:59 -0400838TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600839 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
840 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400841 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700842 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600843 glslangIntermediate(glslangIntermediate)
844{
845 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
846
847 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700848 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600849 stdBuiltins = builder.import("GLSL.std.450");
850 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600851 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
852 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600853
854 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600855 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
856 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600857 builder.addSourceExtension(it->c_str());
858
859 // Add the top-level modes for this shader.
860
John Kessenich92187592016-02-01 13:45:25 -0700861 if (glslangIntermediate->getXfbMode()) {
862 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600863 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700864 }
John Kessenich140f3df2015-06-26 16:58:36 -0600865
866 unsigned int mode;
867 switch (glslangIntermediate->getStage()) {
868 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600869 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600870 break;
871
872 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600873 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600874 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
875 break;
876
877 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600878 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600879 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700880 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
881 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
882 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600883 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600884 }
John Kessenich4016e382016-07-15 11:53:56 -0600885 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600886 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
887
John Kesseniche6903322015-10-13 16:29:02 -0600888 switch (glslangIntermediate->getVertexSpacing()) {
889 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
890 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
891 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600892 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600893 }
John Kessenich4016e382016-07-15 11:53:56 -0600894 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600895 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
896
897 switch (glslangIntermediate->getVertexOrder()) {
898 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
899 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600900 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600901 }
John Kessenich4016e382016-07-15 11:53:56 -0600902 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600903 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
904
905 if (glslangIntermediate->getPointMode())
906 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600907 break;
908
909 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600910 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600911 switch (glslangIntermediate->getInputPrimitive()) {
912 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
913 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
914 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700915 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600916 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600917 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600918 }
John Kessenich4016e382016-07-15 11:53:56 -0600919 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600920 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600921
John Kessenich140f3df2015-06-26 16:58:36 -0600922 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
923
924 switch (glslangIntermediate->getOutputPrimitive()) {
925 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
926 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
927 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600928 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600929 }
John Kessenich4016e382016-07-15 11:53:56 -0600930 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600931 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
932 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
933 break;
934
935 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600936 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600937 if (glslangIntermediate->getPixelCenterInteger())
938 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600939
John Kessenich140f3df2015-06-26 16:58:36 -0600940 if (glslangIntermediate->getOriginUpperLeft())
941 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600942 else
943 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600944
945 if (glslangIntermediate->getEarlyFragmentTests())
946 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
947
948 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600949 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
950 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600951 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600952 }
John Kessenich4016e382016-07-15 11:53:56 -0600953 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600954 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
955
956 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
957 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600958 break;
959
960 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600961 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600962 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
963 glslangIntermediate->getLocalSize(1),
964 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600965 break;
966
967 default:
968 break;
969 }
John Kessenich140f3df2015-06-26 16:58:36 -0600970}
971
John Kessenichfca82622016-11-26 13:23:20 -0700972// Finish creating SPV, after the traversal is complete.
973void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700974{
John Kessenich517fe7a2016-11-26 13:31:47 -0700975 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700976 builder.setBuildPoint(shaderEntry->getLastBlock());
977 builder.leaveFunction();
978 }
979
John Kessenich7ba63412015-12-20 17:37:07 -0700980 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100981 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
982 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700983
qiningda397332016-03-09 19:54:03 -0500984 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700985}
986
John Kessenichfca82622016-11-26 13:23:20 -0700987// Write the SPV into 'out'.
988void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600989{
John Kessenichfca82622016-11-26 13:23:20 -0700990 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600991}
992
993//
994// Implement the traversal functions.
995//
996// Return true from interior nodes to have the external traversal
997// continue on to children. Return false if children were
998// already processed.
999//
1000
1001//
qining25262b32016-05-06 17:25:16 -04001002// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001003// - uniform/input reads
1004// - output writes
1005// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1006// - something simple that degenerates into the last bullet
1007//
1008void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1009{
qining75d1d802016-04-06 14:42:01 -04001010 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1011 if (symbol->getType().getQualifier().isSpecConstant())
1012 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1013
John Kessenich140f3df2015-06-26 16:58:36 -06001014 // getSymbolId() will set up all the IO decorations on the first call.
1015 // Formal function parameters were mapped during makeFunctions().
1016 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001017
1018 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1019 if (builder.isPointer(id)) {
1020 spv::StorageClass sc = builder.getStorageClass(id);
1021 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1022 iOSet.insert(id);
1023 }
1024
1025 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001026 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001027 // Prepare to generate code for the access
1028
1029 // L-value chains will be computed left to right. We're on the symbol now,
1030 // which is the left-most part of the access chain, so now is "clear" time,
1031 // followed by setting the base.
1032 builder.clearAccessChain();
1033
1034 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001035 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001036 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001037 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001038 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001039 // These are also pure R-values.
1040 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001041 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001042 builder.setAccessChainRValue(id);
1043 else
1044 builder.setAccessChainLValue(id);
1045 }
1046}
1047
1048bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1049{
qining40887662016-04-03 22:20:42 -04001050 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1051 if (node->getType().getQualifier().isSpecConstant())
1052 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1053
John Kessenich140f3df2015-06-26 16:58:36 -06001054 // First, handle special cases
1055 switch (node->getOp()) {
1056 case glslang::EOpAssign:
1057 case glslang::EOpAddAssign:
1058 case glslang::EOpSubAssign:
1059 case glslang::EOpMulAssign:
1060 case glslang::EOpVectorTimesMatrixAssign:
1061 case glslang::EOpVectorTimesScalarAssign:
1062 case glslang::EOpMatrixTimesScalarAssign:
1063 case glslang::EOpMatrixTimesMatrixAssign:
1064 case glslang::EOpDivAssign:
1065 case glslang::EOpModAssign:
1066 case glslang::EOpAndAssign:
1067 case glslang::EOpInclusiveOrAssign:
1068 case glslang::EOpExclusiveOrAssign:
1069 case glslang::EOpLeftShiftAssign:
1070 case glslang::EOpRightShiftAssign:
1071 // A bin-op assign "a += b" means the same thing as "a = a + b"
1072 // where a is evaluated before b. For a simple assignment, GLSL
1073 // says to evaluate the left before the right. So, always, left
1074 // node then right node.
1075 {
1076 // get the left l-value, save it away
1077 builder.clearAccessChain();
1078 node->getLeft()->traverse(this);
1079 spv::Builder::AccessChain lValue = builder.getAccessChain();
1080
1081 // evaluate the right
1082 builder.clearAccessChain();
1083 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001084 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001085
1086 if (node->getOp() != glslang::EOpAssign) {
1087 // the left is also an r-value
1088 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001089 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001090
1091 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001092 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001093 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001094 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1095 node->getType().getBasicType());
1096
1097 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001098 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001099 }
1100
1101 // store the result
1102 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001103 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001104
1105 // assignments are expressions having an rValue after they are evaluated...
1106 builder.clearAccessChain();
1107 builder.setAccessChainRValue(rValue);
1108 }
1109 return false;
1110 case glslang::EOpIndexDirect:
1111 case glslang::EOpIndexDirectStruct:
1112 {
1113 // Get the left part of the access chain.
1114 node->getLeft()->traverse(this);
1115
1116 // Add the next element in the chain
1117
David Netoa901ffe2016-06-08 14:11:40 +01001118 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001119 if (! node->getLeft()->getType().isArray() &&
1120 node->getLeft()->getType().isVector() &&
1121 node->getOp() == glslang::EOpIndexDirect) {
1122 // This is essentially a hard-coded vector swizzle of size 1,
1123 // so short circuit the access-chain stuff with a swizzle.
1124 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001125 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001126 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001127 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001128 int spvIndex = glslangIndex;
1129 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1130 node->getOp() == glslang::EOpIndexDirectStruct)
1131 {
1132 // This may be, e.g., an anonymous block-member selection, which generally need
1133 // index remapping due to hidden members in anonymous blocks.
1134 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1135 assert(remapper.size() > 0);
1136 spvIndex = remapper[glslangIndex];
1137 }
John Kessenichebb50532016-05-16 19:22:05 -06001138
David Netoa901ffe2016-06-08 14:11:40 +01001139 // normal case for indexing array or structure or block
1140 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1141
1142 // Add capabilities here for accessing PointSize and clip/cull distance.
1143 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001144 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001145 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001146 }
1147 }
1148 return false;
1149 case glslang::EOpIndexIndirect:
1150 {
1151 // Structure or array or vector indirection.
1152 // Will use native SPIR-V access-chain for struct and array indirection;
1153 // matrices are arrays of vectors, so will also work for a matrix.
1154 // Will use the access chain's 'component' for variable index into a vector.
1155
1156 // This adapter is building access chains left to right.
1157 // Set up the access chain to the left.
1158 node->getLeft()->traverse(this);
1159
1160 // save it so that computing the right side doesn't trash it
1161 spv::Builder::AccessChain partial = builder.getAccessChain();
1162
1163 // compute the next index in the chain
1164 builder.clearAccessChain();
1165 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001166 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001167
1168 // restore the saved access chain
1169 builder.setAccessChain(partial);
1170
1171 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001172 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001173 else
John Kessenichfa668da2015-09-13 14:46:30 -06001174 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001175 }
1176 return false;
1177 case glslang::EOpVectorSwizzle:
1178 {
1179 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001180 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001181 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001182 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001183 }
1184 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001185 case glslang::EOpMatrixSwizzle:
1186 logger->missingFunctionality("matrix swizzle");
1187 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001188 case glslang::EOpLogicalOr:
1189 case glslang::EOpLogicalAnd:
1190 {
1191
1192 // These may require short circuiting, but can sometimes be done as straight
1193 // binary operations. The right operand must be short circuited if it has
1194 // side effects, and should probably be if it is complex.
1195 if (isTrivial(node->getRight()->getAsTyped()))
1196 break; // handle below as a normal binary operation
1197 // otherwise, we need to do dynamic short circuiting on the right operand
1198 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1199 builder.clearAccessChain();
1200 builder.setAccessChainRValue(result);
1201 }
1202 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001203 default:
1204 break;
1205 }
1206
1207 // Assume generic binary op...
1208
John Kessenich32cfd492016-02-02 12:37:46 -07001209 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001210 builder.clearAccessChain();
1211 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001212 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001213
John Kessenich32cfd492016-02-02 12:37:46 -07001214 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001215 builder.clearAccessChain();
1216 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001217 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001218
John Kessenich32cfd492016-02-02 12:37:46 -07001219 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001220 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001221 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001222 convertGlslangToSpvType(node->getType()), left, right,
1223 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001224
John Kessenich50e57562015-12-21 21:21:11 -07001225 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001226 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001227 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001228 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001229 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001230 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001231 return false;
1232 }
John Kessenich140f3df2015-06-26 16:58:36 -06001233}
1234
1235bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1236{
qining40887662016-04-03 22:20:42 -04001237 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1238 if (node->getType().getQualifier().isSpecConstant())
1239 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1240
John Kessenichfc51d282015-08-19 13:34:18 -06001241 spv::Id result = spv::NoResult;
1242
1243 // try texturing first
1244 result = createImageTextureFunctionCall(node);
1245 if (result != spv::NoResult) {
1246 builder.clearAccessChain();
1247 builder.setAccessChainRValue(result);
1248
1249 return false; // done with this node
1250 }
1251
1252 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001253
1254 if (node->getOp() == glslang::EOpArrayLength) {
1255 // Quite special; won't want to evaluate the operand.
1256
1257 // Normal .length() would have been constant folded by the front-end.
1258 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001259 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001260 assert(node->getOperand()->getType().isRuntimeSizedArray());
1261 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1262 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001263 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1264 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001265
1266 builder.clearAccessChain();
1267 builder.setAccessChainRValue(length);
1268
1269 return false;
1270 }
1271
John Kessenichfc51d282015-08-19 13:34:18 -06001272 // Start by evaluating the operand
1273
John Kessenich8c8505c2016-07-26 12:50:38 -06001274 // Does it need a swizzle inversion? If so, evaluation is inverted;
1275 // operate first on the swizzle base, then apply the swizzle.
1276 spv::Id invertedType = spv::NoType;
1277 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1278 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1279 invertedType = getInvertedSwizzleType(*node->getOperand());
1280
John Kessenich140f3df2015-06-26 16:58:36 -06001281 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001282 if (invertedType != spv::NoType)
1283 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1284 else
1285 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001286
Rex Xufc618912015-09-09 16:42:49 +08001287 spv::Id operand = spv::NoResult;
1288
1289 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1290 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001291 node->getOp() == glslang::EOpAtomicCounter ||
1292 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001293 operand = builder.accessChainGetLValue(); // Special case l-value operands
1294 else
John Kessenich32cfd492016-02-02 12:37:46 -07001295 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001296
John Kessenichf6640762016-08-01 19:44:00 -06001297 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001298 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001299
1300 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001301 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001302 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001303
1304 // if not, then possibly an operation
1305 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001306 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001307
1308 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001309 if (invertedType)
1310 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1311
John Kessenich140f3df2015-06-26 16:58:36 -06001312 builder.clearAccessChain();
1313 builder.setAccessChainRValue(result);
1314
1315 return false; // done with this node
1316 }
1317
1318 // it must be a special case, check...
1319 switch (node->getOp()) {
1320 case glslang::EOpPostIncrement:
1321 case glslang::EOpPostDecrement:
1322 case glslang::EOpPreIncrement:
1323 case glslang::EOpPreDecrement:
1324 {
1325 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001326 spv::Id one = 0;
1327 if (node->getBasicType() == glslang::EbtFloat)
1328 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001329 else if (node->getBasicType() == glslang::EbtDouble)
1330 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001331#ifdef AMD_EXTENSIONS
1332 else if (node->getBasicType() == glslang::EbtFloat16)
1333 one = builder.makeFloat16Constant(1.0F);
1334#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001335 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1336 one = builder.makeInt64Constant(1);
1337 else
1338 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001339 glslang::TOperator op;
1340 if (node->getOp() == glslang::EOpPreIncrement ||
1341 node->getOp() == glslang::EOpPostIncrement)
1342 op = glslang::EOpAdd;
1343 else
1344 op = glslang::EOpSub;
1345
John Kessenichf6640762016-08-01 19:44:00 -06001346 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001347 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001348 convertGlslangToSpvType(node->getType()), operand, one,
1349 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001350 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001351
1352 // The result of operation is always stored, but conditionally the
1353 // consumed result. The consumed result is always an r-value.
1354 builder.accessChainStore(result);
1355 builder.clearAccessChain();
1356 if (node->getOp() == glslang::EOpPreIncrement ||
1357 node->getOp() == glslang::EOpPreDecrement)
1358 builder.setAccessChainRValue(result);
1359 else
1360 builder.setAccessChainRValue(operand);
1361 }
1362
1363 return false;
1364
1365 case glslang::EOpEmitStreamVertex:
1366 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1367 return false;
1368 case glslang::EOpEndStreamPrimitive:
1369 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1370 return false;
1371
1372 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001373 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001374 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001375 }
John Kessenich140f3df2015-06-26 16:58:36 -06001376}
1377
1378bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1379{
qining27e04a02016-04-14 16:40:20 -04001380 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1381 if (node->getType().getQualifier().isSpecConstant())
1382 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1383
John Kessenichfc51d282015-08-19 13:34:18 -06001384 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001385 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1386 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001387
1388 // try texturing
1389 result = createImageTextureFunctionCall(node);
1390 if (result != spv::NoResult) {
1391 builder.clearAccessChain();
1392 builder.setAccessChainRValue(result);
1393
1394 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001395 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001396 // "imageStore" is a special case, which has no result
1397 return false;
1398 }
John Kessenichfc51d282015-08-19 13:34:18 -06001399
John Kessenich140f3df2015-06-26 16:58:36 -06001400 glslang::TOperator binOp = glslang::EOpNull;
1401 bool reduceComparison = true;
1402 bool isMatrix = false;
1403 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001404 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001405
1406 assert(node->getOp());
1407
John Kessenichf6640762016-08-01 19:44:00 -06001408 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001409
1410 switch (node->getOp()) {
1411 case glslang::EOpSequence:
1412 {
1413 if (preVisit)
1414 ++sequenceDepth;
1415 else
1416 --sequenceDepth;
1417
1418 if (sequenceDepth == 1) {
1419 // If this is the parent node of all the functions, we want to see them
1420 // early, so all call points have actual SPIR-V functions to reference.
1421 // In all cases, still let the traverser visit the children for us.
1422 makeFunctions(node->getAsAggregate()->getSequence());
1423
John Kessenich6fccb3c2016-09-19 16:01:41 -06001424 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001425 // anything else gets there, so visit out of order, doing them all now.
1426 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1427
John Kessenich6a60c2f2016-12-08 21:01:59 -07001428 // 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 -06001429 // so do them manually.
1430 visitFunctions(node->getAsAggregate()->getSequence());
1431
1432 return false;
1433 }
1434
1435 return true;
1436 }
1437 case glslang::EOpLinkerObjects:
1438 {
1439 if (visit == glslang::EvPreVisit)
1440 linkageOnly = true;
1441 else
1442 linkageOnly = false;
1443
1444 return true;
1445 }
1446 case glslang::EOpComma:
1447 {
1448 // processing from left to right naturally leaves the right-most
1449 // lying around in the access chain
1450 glslang::TIntermSequence& glslangOperands = node->getSequence();
1451 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1452 glslangOperands[i]->traverse(this);
1453
1454 return false;
1455 }
1456 case glslang::EOpFunction:
1457 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001458 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001459 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001460 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001461 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001462 } else {
1463 handleFunctionEntry(node);
1464 }
1465 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001466 if (inEntryPoint)
1467 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001468 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001469 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001470 }
1471
1472 return true;
1473 case glslang::EOpParameters:
1474 // Parameters will have been consumed by EOpFunction processing, but not
1475 // the body, so we still visited the function node's children, making this
1476 // child redundant.
1477 return false;
1478 case glslang::EOpFunctionCall:
1479 {
1480 if (node->isUserDefined())
1481 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001482 // 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 -07001483 if (result) {
1484 builder.clearAccessChain();
1485 builder.setAccessChainRValue(result);
1486 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001487 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001488
1489 return false;
1490 }
1491 case glslang::EOpConstructMat2x2:
1492 case glslang::EOpConstructMat2x3:
1493 case glslang::EOpConstructMat2x4:
1494 case glslang::EOpConstructMat3x2:
1495 case glslang::EOpConstructMat3x3:
1496 case glslang::EOpConstructMat3x4:
1497 case glslang::EOpConstructMat4x2:
1498 case glslang::EOpConstructMat4x3:
1499 case glslang::EOpConstructMat4x4:
1500 case glslang::EOpConstructDMat2x2:
1501 case glslang::EOpConstructDMat2x3:
1502 case glslang::EOpConstructDMat2x4:
1503 case glslang::EOpConstructDMat3x2:
1504 case glslang::EOpConstructDMat3x3:
1505 case glslang::EOpConstructDMat3x4:
1506 case glslang::EOpConstructDMat4x2:
1507 case glslang::EOpConstructDMat4x3:
1508 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001509#ifdef AMD_EXTENSIONS
1510 case glslang::EOpConstructF16Mat2x2:
1511 case glslang::EOpConstructF16Mat2x3:
1512 case glslang::EOpConstructF16Mat2x4:
1513 case glslang::EOpConstructF16Mat3x2:
1514 case glslang::EOpConstructF16Mat3x3:
1515 case glslang::EOpConstructF16Mat3x4:
1516 case glslang::EOpConstructF16Mat4x2:
1517 case glslang::EOpConstructF16Mat4x3:
1518 case glslang::EOpConstructF16Mat4x4:
1519#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001520 isMatrix = true;
1521 // fall through
1522 case glslang::EOpConstructFloat:
1523 case glslang::EOpConstructVec2:
1524 case glslang::EOpConstructVec3:
1525 case glslang::EOpConstructVec4:
1526 case glslang::EOpConstructDouble:
1527 case glslang::EOpConstructDVec2:
1528 case glslang::EOpConstructDVec3:
1529 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001530#ifdef AMD_EXTENSIONS
1531 case glslang::EOpConstructFloat16:
1532 case glslang::EOpConstructF16Vec2:
1533 case glslang::EOpConstructF16Vec3:
1534 case glslang::EOpConstructF16Vec4:
1535#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001536 case glslang::EOpConstructBool:
1537 case glslang::EOpConstructBVec2:
1538 case glslang::EOpConstructBVec3:
1539 case glslang::EOpConstructBVec4:
1540 case glslang::EOpConstructInt:
1541 case glslang::EOpConstructIVec2:
1542 case glslang::EOpConstructIVec3:
1543 case glslang::EOpConstructIVec4:
1544 case glslang::EOpConstructUint:
1545 case glslang::EOpConstructUVec2:
1546 case glslang::EOpConstructUVec3:
1547 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001548 case glslang::EOpConstructInt64:
1549 case glslang::EOpConstructI64Vec2:
1550 case glslang::EOpConstructI64Vec3:
1551 case glslang::EOpConstructI64Vec4:
1552 case glslang::EOpConstructUint64:
1553 case glslang::EOpConstructU64Vec2:
1554 case glslang::EOpConstructU64Vec3:
1555 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001556 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001557 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001558 {
1559 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001560 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001561 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001562 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001563 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001564 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001565 std::vector<spv::Id> constituents;
1566 for (int c = 0; c < (int)arguments.size(); ++c)
1567 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001568 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001569 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001570 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001571 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001572 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001573
1574 builder.clearAccessChain();
1575 builder.setAccessChainRValue(constructed);
1576
1577 return false;
1578 }
1579
1580 // These six are component-wise compares with component-wise results.
1581 // Forward on to createBinaryOperation(), requesting a vector result.
1582 case glslang::EOpLessThan:
1583 case glslang::EOpGreaterThan:
1584 case glslang::EOpLessThanEqual:
1585 case glslang::EOpGreaterThanEqual:
1586 case glslang::EOpVectorEqual:
1587 case glslang::EOpVectorNotEqual:
1588 {
1589 // Map the operation to a binary
1590 binOp = node->getOp();
1591 reduceComparison = false;
1592 switch (node->getOp()) {
1593 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1594 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1595 default: binOp = node->getOp(); break;
1596 }
1597
1598 break;
1599 }
1600 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001601 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001602 binOp = glslang::EOpMul;
1603 break;
1604 case glslang::EOpOuterProduct:
1605 // two vectors multiplied to make a matrix
1606 binOp = glslang::EOpOuterProduct;
1607 break;
1608 case glslang::EOpDot:
1609 {
qining25262b32016-05-06 17:25:16 -04001610 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001611 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001612 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001613 binOp = glslang::EOpMul;
1614 break;
1615 }
1616 case glslang::EOpMod:
1617 // when an aggregate, this is the floating-point mod built-in function,
1618 // which can be emitted by the one in createBinaryOperation()
1619 binOp = glslang::EOpMod;
1620 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001621 case glslang::EOpEmitVertex:
1622 case glslang::EOpEndPrimitive:
1623 case glslang::EOpBarrier:
1624 case glslang::EOpMemoryBarrier:
1625 case glslang::EOpMemoryBarrierAtomicCounter:
1626 case glslang::EOpMemoryBarrierBuffer:
1627 case glslang::EOpMemoryBarrierImage:
1628 case glslang::EOpMemoryBarrierShared:
1629 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001630 case glslang::EOpAllMemoryBarrierWithGroupSync:
1631 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1632 case glslang::EOpWorkgroupMemoryBarrier:
1633 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001634 noReturnValue = true;
1635 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1636 break;
1637
John Kessenich426394d2015-07-23 10:22:48 -06001638 case glslang::EOpAtomicAdd:
1639 case glslang::EOpAtomicMin:
1640 case glslang::EOpAtomicMax:
1641 case glslang::EOpAtomicAnd:
1642 case glslang::EOpAtomicOr:
1643 case glslang::EOpAtomicXor:
1644 case glslang::EOpAtomicExchange:
1645 case glslang::EOpAtomicCompSwap:
1646 atomic = true;
1647 break;
1648
John Kessenich140f3df2015-06-26 16:58:36 -06001649 default:
1650 break;
1651 }
1652
1653 //
1654 // See if it maps to a regular operation.
1655 //
John Kessenich140f3df2015-06-26 16:58:36 -06001656 if (binOp != glslang::EOpNull) {
1657 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1658 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1659 assert(left && right);
1660
1661 builder.clearAccessChain();
1662 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001663 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001664
1665 builder.clearAccessChain();
1666 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001667 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001668
qining25262b32016-05-06 17:25:16 -04001669 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001670 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001671 left->getType().getBasicType(), reduceComparison);
1672
1673 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001674 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001675 builder.clearAccessChain();
1676 builder.setAccessChainRValue(result);
1677
1678 return false;
1679 }
1680
John Kessenich426394d2015-07-23 10:22:48 -06001681 //
1682 // Create the list of operands.
1683 //
John Kessenich140f3df2015-06-26 16:58:36 -06001684 glslang::TIntermSequence& glslangOperands = node->getSequence();
1685 std::vector<spv::Id> operands;
1686 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001687 // special case l-value operands; there are just a few
1688 bool lvalue = false;
1689 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001690 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001691 case glslang::EOpModf:
1692 if (arg == 1)
1693 lvalue = true;
1694 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001695 case glslang::EOpInterpolateAtSample:
1696 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001697#ifdef AMD_EXTENSIONS
1698 case glslang::EOpInterpolateAtVertex:
1699#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001700 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001701 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001702
1703 // Does it need a swizzle inversion? If so, evaluation is inverted;
1704 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001705 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001706 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1707 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1708 }
Rex Xu7a26c172015-12-08 17:12:09 +08001709 break;
Rex Xud4782c12015-09-06 16:30:11 +08001710 case glslang::EOpAtomicAdd:
1711 case glslang::EOpAtomicMin:
1712 case glslang::EOpAtomicMax:
1713 case glslang::EOpAtomicAnd:
1714 case glslang::EOpAtomicOr:
1715 case glslang::EOpAtomicXor:
1716 case glslang::EOpAtomicExchange:
1717 case glslang::EOpAtomicCompSwap:
1718 if (arg == 0)
1719 lvalue = true;
1720 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001721 case glslang::EOpAddCarry:
1722 case glslang::EOpSubBorrow:
1723 if (arg == 2)
1724 lvalue = true;
1725 break;
1726 case glslang::EOpUMulExtended:
1727 case glslang::EOpIMulExtended:
1728 if (arg >= 2)
1729 lvalue = true;
1730 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001731 default:
1732 break;
1733 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001734 builder.clearAccessChain();
1735 if (invertedType != spv::NoType && arg == 0)
1736 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1737 else
1738 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001739 if (lvalue)
1740 operands.push_back(builder.accessChainGetLValue());
1741 else
John Kessenich32cfd492016-02-02 12:37:46 -07001742 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001743 }
John Kessenich426394d2015-07-23 10:22:48 -06001744
1745 if (atomic) {
1746 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001747 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001748 } else {
1749 // Pass through to generic operations.
1750 switch (glslangOperands.size()) {
1751 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001752 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001753 break;
1754 case 1:
qining25262b32016-05-06 17:25:16 -04001755 result = createUnaryOperation(
1756 node->getOp(), precision,
1757 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001758 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001759 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001760 break;
1761 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001762 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001763 break;
1764 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001765 if (invertedType)
1766 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001767 }
1768
1769 if (noReturnValue)
1770 return false;
1771
1772 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001773 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001774 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001775 } else {
1776 builder.clearAccessChain();
1777 builder.setAccessChainRValue(result);
1778 return false;
1779 }
1780}
1781
John Kessenich433e9ff2017-01-26 20:31:11 -07001782// This path handles both if-then-else and ?:
1783// The if-then-else has a node type of void, while
1784// ?: has either a void or a non-void node type
1785//
1786// Leaving the result, when not void:
1787// GLSL only has r-values as the result of a :?, but
1788// if we have an l-value, that can be more efficient if it will
1789// become the base of a complex r-value expression, because the
1790// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001791bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1792{
John Kessenich433e9ff2017-01-26 20:31:11 -07001793 // See if it simple and safe to generate OpSelect instead of using control flow.
1794 // Crucially, side effects must be avoided, and there are performance trade-offs.
1795 // Return true if good idea (and safe) for OpSelect, false otherwise.
1796 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001797 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1798 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001799 return false;
1800
1801 if (node->getTrueBlock() == nullptr ||
1802 node->getFalseBlock() == nullptr)
1803 return false;
1804
1805 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1806 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1807
1808 // return true if a single operand to ? : is okay for OpSelect
1809 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001810 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001811 };
1812
1813 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1814 operandOkay(node->getFalseBlock()->getAsTyped());
1815 };
1816
1817 // Emit OpSelect for this selection.
1818 const auto handleAsOpSelect = [&]() {
1819 node->getCondition()->traverse(this);
1820 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1821 node->getTrueBlock()->traverse(this);
1822 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1823 node->getFalseBlock()->traverse(this);
1824 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1825
1826 spv::Id select = builder.createTriOp(spv::OpSelect, convertGlslangToSpvType(node->getType()), condition, trueValue, falseValue);
1827 builder.clearAccessChain();
1828 builder.setAccessChainRValue(select);
1829 };
1830
1831 // Try for OpSelect
1832
1833 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001834 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1835 if (node->getType().getQualifier().isSpecConstant())
1836 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1837
John Kessenich433e9ff2017-01-26 20:31:11 -07001838 handleAsOpSelect();
1839 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001840 }
1841
John Kessenich433e9ff2017-01-26 20:31:11 -07001842 // Instead, emit control flow...
1843
1844 // Don't handle results as temporaries, because there will be two names
1845 // and better to leave SSA to later passes.
1846 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1847 ? spv::NoResult
1848 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1849
John Kessenich140f3df2015-06-26 16:58:36 -06001850 // emit the condition before doing anything with selection
1851 node->getCondition()->traverse(this);
1852
1853 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001854 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001855
John Kessenich433e9ff2017-01-26 20:31:11 -07001856 // emit the "then" statement
1857 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001858 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001859 if (result != spv::NoResult)
1860 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001861 }
1862
John Kessenich433e9ff2017-01-26 20:31:11 -07001863 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001864 ifBuilder.makeBeginElse();
1865 // emit the "else" statement
1866 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001867 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001868 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001869 }
1870
John Kessenich433e9ff2017-01-26 20:31:11 -07001871 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001872 ifBuilder.makeEndIf();
1873
John Kessenich433e9ff2017-01-26 20:31:11 -07001874 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001875 // GLSL only has r-values as the result of a :?, but
1876 // if we have an l-value, that can be more efficient if it will
1877 // become the base of a complex r-value expression, because the
1878 // next layer copies r-values into memory to use the access-chain mechanism
1879 builder.clearAccessChain();
1880 builder.setAccessChainLValue(result);
1881 }
1882
1883 return false;
1884}
1885
1886bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1887{
1888 // emit and get the condition before doing anything with switch
1889 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001890 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001891
1892 // browse the children to sort out code segments
1893 int defaultSegment = -1;
1894 std::vector<TIntermNode*> codeSegments;
1895 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1896 std::vector<int> caseValues;
1897 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1898 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1899 TIntermNode* child = *c;
1900 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001901 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001902 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001903 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001904 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1905 } else
1906 codeSegments.push_back(child);
1907 }
1908
qining25262b32016-05-06 17:25:16 -04001909 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001910 // statements between the last case and the end of the switch statement
1911 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1912 (int)codeSegments.size() == defaultSegment)
1913 codeSegments.push_back(nullptr);
1914
1915 // make the switch statement
1916 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001917 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001918
1919 // emit all the code in the segments
1920 breakForLoop.push(false);
1921 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1922 builder.nextSwitchSegment(segmentBlocks, s);
1923 if (codeSegments[s])
1924 codeSegments[s]->traverse(this);
1925 else
1926 builder.addSwitchBreak();
1927 }
1928 breakForLoop.pop();
1929
1930 builder.endSwitch(segmentBlocks);
1931
1932 return false;
1933}
1934
1935void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1936{
1937 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001938 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001939
1940 builder.clearAccessChain();
1941 builder.setAccessChainRValue(constant);
1942}
1943
1944bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1945{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001946 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001947 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001948 // Spec requires back edges to target header blocks, and every header block
1949 // must dominate its merge block. Make a header block first to ensure these
1950 // conditions are met. By definition, it will contain OpLoopMerge, followed
1951 // by a block-ending branch. But we don't want to put any other body/test
1952 // instructions in it, since the body/test may have arbitrary instructions,
1953 // including merges of its own.
1954 builder.setBuildPoint(&blocks.head);
1955 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001956 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001957 spv::Block& test = builder.makeNewBlock();
1958 builder.createBranch(&test);
1959
1960 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001961 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001962 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001963 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001964 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1965
1966 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001967 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001968 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001969 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001970 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001971 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001972
1973 builder.setBuildPoint(&blocks.continue_target);
1974 if (node->getTerminal())
1975 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001976 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001977 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001978 builder.createBranch(&blocks.body);
1979
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001980 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001981 builder.setBuildPoint(&blocks.body);
1982 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001983 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001984 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001985 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001986
1987 builder.setBuildPoint(&blocks.continue_target);
1988 if (node->getTerminal())
1989 node->getTerminal()->traverse(this);
1990 if (node->getTest()) {
1991 node->getTest()->traverse(this);
1992 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001993 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001994 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001995 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001996 // TODO: unless there was a break/return/discard instruction
1997 // somewhere in the body, this is an infinite loop, so we should
1998 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001999 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002000 }
John Kessenich140f3df2015-06-26 16:58:36 -06002001 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002002 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002003 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002004 return false;
2005}
2006
2007bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2008{
2009 if (node->getExpression())
2010 node->getExpression()->traverse(this);
2011
2012 switch (node->getFlowOp()) {
2013 case glslang::EOpKill:
2014 builder.makeDiscard();
2015 break;
2016 case glslang::EOpBreak:
2017 if (breakForLoop.top())
2018 builder.createLoopExit();
2019 else
2020 builder.addSwitchBreak();
2021 break;
2022 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002023 builder.createLoopContinue();
2024 break;
2025 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002026 if (node->getExpression()) {
2027 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2028 spv::Id returnId = accessChainLoad(glslangReturnType);
2029 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2030 builder.clearAccessChain();
2031 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2032 builder.setAccessChainLValue(copyId);
2033 multiTypeStore(glslangReturnType, returnId);
2034 returnId = builder.createLoad(copyId);
2035 }
2036 builder.makeReturn(false, returnId);
2037 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002038 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002039
2040 builder.clearAccessChain();
2041 break;
2042
2043 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002044 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002045 break;
2046 }
2047
2048 return false;
2049}
2050
2051spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2052{
qining25262b32016-05-06 17:25:16 -04002053 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002054 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002055 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002056 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002057 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002058 }
2059
2060 // Now, handle actual variables
2061 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
2062 spv::Id spvType = convertGlslangToSpvType(node->getType());
2063
2064 const char* name = node->getName().c_str();
2065 if (glslang::IsAnonymous(name))
2066 name = "";
2067
2068 return builder.createVariable(storageClass, spvType, name);
2069}
2070
2071// Return type Id of the sampled type.
2072spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2073{
2074 switch (sampler.type) {
2075 case glslang::EbtFloat: return builder.makeFloatType(32);
2076 case glslang::EbtInt: return builder.makeIntType(32);
2077 case glslang::EbtUint: return builder.makeUintType(32);
2078 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002079 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002080 return builder.makeFloatType(32);
2081 }
2082}
2083
John Kessenich8c8505c2016-07-26 12:50:38 -06002084// If node is a swizzle operation, return the type that should be used if
2085// the swizzle base is first consumed by another operation, before the swizzle
2086// is applied.
2087spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2088{
John Kessenichecba76f2017-01-06 00:34:48 -07002089 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002090 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2091 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2092 else
2093 return spv::NoType;
2094}
2095
2096// When inverting a swizzle with a parent op, this function
2097// will apply the swizzle operation to a completed parent operation.
2098spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2099{
2100 std::vector<unsigned> swizzle;
2101 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2102 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2103}
2104
John Kessenich8c8505c2016-07-26 12:50:38 -06002105// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2106void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2107{
2108 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2109 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2110 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2111}
2112
John Kessenich3ac051e2015-12-20 11:29:16 -07002113// Convert from a glslang type to an SPV type, by calling into a
2114// recursive version of this function. This establishes the inherited
2115// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002116spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2117{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002118 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002119}
2120
2121// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002122// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002123// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002124spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002125{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002126 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002127
2128 switch (type.getBasicType()) {
2129 case glslang::EbtVoid:
2130 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002131 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002132 break;
2133 case glslang::EbtFloat:
2134 spvType = builder.makeFloatType(32);
2135 break;
2136 case glslang::EbtDouble:
2137 spvType = builder.makeFloatType(64);
2138 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002139#ifdef AMD_EXTENSIONS
2140 case glslang::EbtFloat16:
2141 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002142 spvType = builder.makeFloatType(16);
2143 break;
2144#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002145 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002146 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2147 // a 32-bit int where non-0 means true.
2148 if (explicitLayout != glslang::ElpNone)
2149 spvType = builder.makeUintType(32);
2150 else
2151 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002152 break;
2153 case glslang::EbtInt:
2154 spvType = builder.makeIntType(32);
2155 break;
2156 case glslang::EbtUint:
2157 spvType = builder.makeUintType(32);
2158 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002159 case glslang::EbtInt64:
2160 builder.addCapability(spv::CapabilityInt64);
2161 spvType = builder.makeIntType(64);
2162 break;
2163 case glslang::EbtUint64:
2164 builder.addCapability(spv::CapabilityInt64);
2165 spvType = builder.makeUintType(64);
2166 break;
John Kessenich426394d2015-07-23 10:22:48 -06002167 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002168 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002169 spvType = builder.makeUintType(32);
2170 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002171 case glslang::EbtSampler:
2172 {
2173 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002174 if (sampler.sampler) {
2175 // pure sampler
2176 spvType = builder.makeSamplerType();
2177 } else {
2178 // an image is present, make its type
2179 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2180 sampler.image ? 2 : 1, TranslateImageFormat(type));
2181 if (sampler.combined) {
2182 // already has both image and sampler, make the combined type
2183 spvType = builder.makeSampledImageType(spvType);
2184 }
John Kessenich55e7d112015-11-15 21:33:39 -07002185 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002186 }
John Kessenich140f3df2015-06-26 16:58:36 -06002187 break;
2188 case glslang::EbtStruct:
2189 case glslang::EbtBlock:
2190 {
2191 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002192 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002193
2194 // Try to share structs for different layouts, but not yet for other
2195 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002196 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002197 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002198 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002199 break;
2200
2201 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002202 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002203 memberRemapper[glslangMembers].resize(glslangMembers->size());
2204 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002205 }
2206 break;
2207 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002208 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002209 break;
2210 }
2211
2212 if (type.isMatrix())
2213 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2214 else {
2215 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2216 if (type.getVectorSize() > 1)
2217 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2218 }
2219
2220 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002221 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2222
John Kessenichc9a80832015-09-12 12:17:44 -06002223 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002224 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002225 // We need to decorate array strides for types needing explicit layout, except blocks.
2226 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002227 // Use a dummy glslang type for querying internal strides of
2228 // arrays of arrays, but using just a one-dimensional array.
2229 glslang::TType simpleArrayType(type, 0); // deference type of the array
2230 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2231 simpleArrayType.getArraySizes().dereference();
2232
2233 // Will compute the higher-order strides here, rather than making a whole
2234 // pile of types and doing repetitive recursion on their contents.
2235 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2236 }
John Kessenichf8842e52016-01-04 19:22:56 -07002237
2238 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002239 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002240 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002241 if (stride > 0)
2242 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002243 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002244 }
2245 } else {
2246 // single-dimensional array, and don't yet have stride
2247
John Kessenichf8842e52016-01-04 19:22:56 -07002248 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002249 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2250 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002251 }
John Kessenich31ed4832015-09-09 17:51:38 -06002252
John Kessenichc9a80832015-09-12 12:17:44 -06002253 // Do the outer dimension, which might not be known for a runtime-sized array
2254 if (type.isRuntimeSizedArray()) {
2255 spvType = builder.makeRuntimeArray(spvType);
2256 } else {
2257 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002258 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002259 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002260 if (stride > 0)
2261 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002262 }
2263
2264 return spvType;
2265}
2266
John Kessenich0e737842017-03-24 18:38:16 -06002267// TODO: this functionality should exist at a higher level, in creating the AST
2268//
2269// Identify interface members that don't have their required extension turned on.
2270//
2271bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2272{
2273 auto& extensions = glslangIntermediate->getRequestedExtensions();
2274
Rex Xubcf291a2017-03-29 23:01:36 +08002275 if (member.getFieldName() == "gl_ViewportMask" &&
2276 extensions.find("GL_NV_viewport_array2") == extensions.end())
2277 return true;
2278 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2279 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2280 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002281 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2282 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2283 return true;
2284 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2285 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2286 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002287 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2288 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2289 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002290
2291 return false;
2292};
2293
John Kessenich6090df02016-06-30 21:18:02 -06002294// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2295// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2296// Mutually recursive with convertGlslangToSpvType().
2297spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2298 const glslang::TTypeList* glslangMembers,
2299 glslang::TLayoutPacking explicitLayout,
2300 const glslang::TQualifier& qualifier)
2301{
2302 // Create a vector of struct types for SPIR-V to consume
2303 std::vector<spv::Id> spvMembers;
2304 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2305 int locationOffset = 0; // for use across struct members, when they are called recursively
2306 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2307 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2308 if (glslangMember.hiddenMember()) {
2309 ++memberDelta;
2310 if (type.getBasicType() == glslang::EbtBlock)
2311 memberRemapper[glslangMembers][i] = -1;
2312 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002313 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002314 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002315 if (filterMember(glslangMember))
2316 continue;
2317 }
John Kessenich6090df02016-06-30 21:18:02 -06002318 // modify just this child's view of the qualifier
2319 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2320 InheritQualifiers(memberQualifier, qualifier);
2321
2322 // manually inherit location; it's more complex
2323 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2324 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2325 if (qualifier.hasLocation())
2326 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2327
2328 // recurse
2329 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2330 }
2331 }
2332
2333 // Make the SPIR-V type
2334 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002335 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002336 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2337
2338 // Decorate it
2339 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2340
2341 return spvType;
2342}
2343
2344void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2345 const glslang::TTypeList* glslangMembers,
2346 glslang::TLayoutPacking explicitLayout,
2347 const glslang::TQualifier& qualifier,
2348 spv::Id spvType)
2349{
2350 // Name and decorate the non-hidden members
2351 int offset = -1;
2352 int locationOffset = 0; // for use within the members of this struct
2353 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2354 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2355 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002356 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002357 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002358 if (filterMember(glslangMember))
2359 continue;
2360 }
John Kessenich6090df02016-06-30 21:18:02 -06002361
2362 // modify just this child's view of the qualifier
2363 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2364 InheritQualifiers(memberQualifier, qualifier);
2365
2366 // using -1 above to indicate a hidden member
2367 if (member >= 0) {
2368 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2369 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2370 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2371 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002372 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2373 type.getQualifier().storage == glslang::EvqVaryingOut) {
2374 if (type.getBasicType() == glslang::EbtBlock ||
2375 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002376 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2377 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2378 }
2379 }
2380 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2381
2382 if (qualifier.storage == glslang::EvqBuffer) {
2383 std::vector<spv::Decoration> memory;
2384 TranslateMemoryDecoration(memberQualifier, memory);
2385 for (unsigned int i = 0; i < memory.size(); ++i)
2386 addMemberDecoration(spvType, member, memory[i]);
2387 }
2388
John Kessenich2f47bc92016-06-30 21:47:35 -06002389 // Compute location decoration; tricky based on whether inheritance is at play and
2390 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002391 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2392 // probably move to the linker stage of the front end proper, and just have the
2393 // answer sitting already distributed throughout the individual member locations.
2394 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002395 // Ignore member locations if the container is an array, as that's
2396 // ill-specified and decisions have been made to not allow this anyway.
2397 // The object itself must have a location, and that comes out from decorating the object,
2398 // not the type (this code decorates types).
2399 if (! type.isArray()) {
2400 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2401 // struct members should not have explicit locations
2402 assert(type.getBasicType() != glslang::EbtStruct);
2403 location = memberQualifier.layoutLocation;
2404 } else if (type.getBasicType() != glslang::EbtBlock) {
2405 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2406 // The members, and their nested types, must not themselves have Location decorations.
2407 } else if (qualifier.hasLocation()) // inheritance
2408 location = qualifier.layoutLocation + locationOffset;
2409 }
John Kessenich6090df02016-06-30 21:18:02 -06002410 if (location >= 0)
2411 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2412
John Kessenich2f47bc92016-06-30 21:47:35 -06002413 if (qualifier.hasLocation()) // track for upcoming inheritance
2414 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2415
John Kessenich6090df02016-06-30 21:18:02 -06002416 // component, XFB, others
2417 if (glslangMember.getQualifier().hasComponent())
2418 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2419 if (glslangMember.getQualifier().hasXfbOffset())
2420 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2421 else if (explicitLayout != glslang::ElpNone) {
2422 // figure out what to do with offset, which is accumulating
2423 int nextOffset;
2424 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2425 if (offset >= 0)
2426 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2427 offset = nextOffset;
2428 }
2429
2430 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2431 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2432
2433 // built-in variable decorations
2434 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002435 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002436 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002437
2438#ifdef NV_EXTENSIONS
2439 if (builtIn == spv::BuiltInLayer) {
2440 // SPV_NV_viewport_array2 extension
2441 if (glslangMember.getQualifier().layoutViewportRelative){
2442 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2443 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2444 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2445 }
2446 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2447 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2448 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2449 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2450 }
2451 }
chaocdf3956c2017-02-14 14:52:34 -08002452 if (glslangMember.getQualifier().layoutPassthrough) {
2453 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2454 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2455 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2456 }
chaoc771d89f2017-01-13 01:10:53 -08002457#endif
John Kessenich6090df02016-06-30 21:18:02 -06002458 }
2459 }
2460
2461 // Decorate the structure
2462 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2463 addDecoration(spvType, TranslateBlockDecoration(type));
2464 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2465 builder.addCapability(spv::CapabilityGeometryStreams);
2466 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2467 }
2468 if (glslangIntermediate->getXfbMode()) {
2469 builder.addCapability(spv::CapabilityTransformFeedback);
2470 if (type.getQualifier().hasXfbStride())
2471 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2472 if (type.getQualifier().hasXfbBuffer())
2473 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2474 }
2475}
2476
John Kessenich6c292d32016-02-15 20:58:50 -07002477// Turn the expression forming the array size into an id.
2478// This is not quite trivial, because of specialization constants.
2479// Sometimes, a raw constant is turned into an Id, and sometimes
2480// a specialization constant expression is.
2481spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2482{
2483 // First, see if this is sized with a node, meaning a specialization constant:
2484 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2485 if (specNode != nullptr) {
2486 builder.clearAccessChain();
2487 specNode->traverse(this);
2488 return accessChainLoad(specNode->getAsTyped()->getType());
2489 }
qining25262b32016-05-06 17:25:16 -04002490
John Kessenich6c292d32016-02-15 20:58:50 -07002491 // Otherwise, need a compile-time (front end) size, get it:
2492 int size = arraySizes.getDimSize(dim);
2493 assert(size > 0);
2494 return builder.makeUintConstant(size);
2495}
2496
John Kessenich103bef92016-02-08 21:38:15 -07002497// Wrap the builder's accessChainLoad to:
2498// - localize handling of RelaxedPrecision
2499// - use the SPIR-V inferred type instead of another conversion of the glslang type
2500// (avoids unnecessary work and possible type punning for structures)
2501// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002502spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2503{
John Kessenich103bef92016-02-08 21:38:15 -07002504 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2505 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2506
2507 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002508 if (type.getBasicType() == glslang::EbtBool) {
2509 if (builder.isScalarType(nominalTypeId)) {
2510 // Conversion for bool
2511 spv::Id boolType = builder.makeBoolType();
2512 if (nominalTypeId != boolType)
2513 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2514 } else if (builder.isVectorType(nominalTypeId)) {
2515 // Conversion for bvec
2516 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2517 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2518 if (nominalTypeId != bvecType)
2519 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2520 }
2521 }
John Kessenich103bef92016-02-08 21:38:15 -07002522
2523 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002524}
2525
Rex Xu27253232016-02-23 17:51:09 +08002526// Wrap the builder's accessChainStore to:
2527// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002528//
2529// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002530void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2531{
2532 // Need to convert to abstract types when necessary
2533 if (type.getBasicType() == glslang::EbtBool) {
2534 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2535
2536 if (builder.isScalarType(nominalTypeId)) {
2537 // Conversion for bool
2538 spv::Id boolType = builder.makeBoolType();
2539 if (nominalTypeId != boolType) {
2540 spv::Id zero = builder.makeUintConstant(0);
2541 spv::Id one = builder.makeUintConstant(1);
2542 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2543 }
2544 } else if (builder.isVectorType(nominalTypeId)) {
2545 // Conversion for bvec
2546 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2547 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2548 if (nominalTypeId != bvecType) {
2549 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2550 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2551 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2552 }
2553 }
2554 }
2555
2556 builder.accessChainStore(rvalue);
2557}
2558
John Kessenich4bf71552016-09-02 11:20:21 -06002559// For storing when types match at the glslang level, but not might match at the
2560// SPIR-V level.
2561//
2562// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002563// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002564// as in a member-decorated way.
2565//
2566// NOTE: This function can handle any store request; if it's not special it
2567// simplifies to a simple OpStore.
2568//
2569// Implicitly uses the existing builder.accessChain as the storage target.
2570void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2571{
John Kessenichb3e24e42016-09-11 12:33:43 -06002572 // we only do the complex path here if it's an aggregate
2573 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002574 accessChainStore(type, rValue);
2575 return;
2576 }
2577
John Kessenichb3e24e42016-09-11 12:33:43 -06002578 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002579 spv::Id rType = builder.getTypeId(rValue);
2580 spv::Id lValue = builder.accessChainGetLValue();
2581 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2582 if (lType == rType) {
2583 accessChainStore(type, rValue);
2584 return;
2585 }
2586
John Kessenichb3e24e42016-09-11 12:33:43 -06002587 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002588 // where the two types were the same type in GLSL. This requires member
2589 // by member copy, recursively.
2590
John Kessenichb3e24e42016-09-11 12:33:43 -06002591 // If an array, copy element by element.
2592 if (type.isArray()) {
2593 glslang::TType glslangElementType(type, 0);
2594 spv::Id elementRType = builder.getContainedTypeId(rType);
2595 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2596 // get the source member
2597 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002598
John Kessenichb3e24e42016-09-11 12:33:43 -06002599 // set up the target storage
2600 builder.clearAccessChain();
2601 builder.setAccessChainLValue(lValue);
2602 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002603
John Kessenichb3e24e42016-09-11 12:33:43 -06002604 // store the member
2605 multiTypeStore(glslangElementType, elementRValue);
2606 }
2607 } else {
2608 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002609
John Kessenichb3e24e42016-09-11 12:33:43 -06002610 // loop over structure members
2611 const glslang::TTypeList& members = *type.getStruct();
2612 for (int m = 0; m < (int)members.size(); ++m) {
2613 const glslang::TType& glslangMemberType = *members[m].type;
2614
2615 // get the source member
2616 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2617 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2618
2619 // set up the target storage
2620 builder.clearAccessChain();
2621 builder.setAccessChainLValue(lValue);
2622 builder.accessChainPush(builder.makeIntConstant(m));
2623
2624 // store the member
2625 multiTypeStore(glslangMemberType, memberRValue);
2626 }
John Kessenich4bf71552016-09-02 11:20:21 -06002627 }
2628}
2629
John Kessenichf85e8062015-12-19 13:57:10 -07002630// Decide whether or not this type should be
2631// decorated with offsets and strides, and if so
2632// whether std140 or std430 rules should be applied.
2633glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002634{
John Kessenichf85e8062015-12-19 13:57:10 -07002635 // has to be a block
2636 if (type.getBasicType() != glslang::EbtBlock)
2637 return glslang::ElpNone;
2638
2639 // has to be a uniform or buffer block
2640 if (type.getQualifier().storage != glslang::EvqUniform &&
2641 type.getQualifier().storage != glslang::EvqBuffer)
2642 return glslang::ElpNone;
2643
2644 // return the layout to use
2645 switch (type.getQualifier().layoutPacking) {
2646 case glslang::ElpStd140:
2647 case glslang::ElpStd430:
2648 return type.getQualifier().layoutPacking;
2649 default:
2650 return glslang::ElpNone;
2651 }
John Kessenich31ed4832015-09-09 17:51:38 -06002652}
2653
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002654// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002655int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002656{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002657 int size;
John Kessenich49987892015-12-29 17:11:44 -07002658 int stride;
2659 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002660
2661 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002662}
2663
John Kessenich49987892015-12-29 17:11:44 -07002664// 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 -07002665// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002666int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002667{
John Kessenich49987892015-12-29 17:11:44 -07002668 glslang::TType elementType;
2669 elementType.shallowCopy(matrixType);
2670 elementType.clearArraySizes();
2671
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002672 int size;
John Kessenich49987892015-12-29 17:11:44 -07002673 int stride;
2674 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2675
2676 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002677}
2678
John Kessenich5e4b1242015-08-06 22:53:06 -06002679// Given a member type of a struct, realign the current offset for it, and compute
2680// the next (not yet aligned) offset for the next member, which will get aligned
2681// on the next call.
2682// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2683// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2684// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002685void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002686 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002687{
2688 // this will get a positive value when deemed necessary
2689 nextOffset = -1;
2690
John Kessenich5e4b1242015-08-06 22:53:06 -06002691 // override anything in currentOffset with user-set offset
2692 if (memberType.getQualifier().hasOffset())
2693 currentOffset = memberType.getQualifier().layoutOffset;
2694
2695 // It could be that current linker usage in glslang updated all the layoutOffset,
2696 // in which case the following code does not matter. But, that's not quite right
2697 // once cross-compilation unit GLSL validation is done, as the original user
2698 // settings are needed in layoutOffset, and then the following will come into play.
2699
John Kessenichf85e8062015-12-19 13:57:10 -07002700 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002701 if (! memberType.getQualifier().hasOffset())
2702 currentOffset = -1;
2703
2704 return;
2705 }
2706
John Kessenichf85e8062015-12-19 13:57:10 -07002707 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002708 if (currentOffset < 0)
2709 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002710
John Kessenich5e4b1242015-08-06 22:53:06 -06002711 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2712 // but possibly not yet correctly aligned.
2713
2714 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002715 int dummyStride;
2716 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002717 glslang::RoundToPow2(currentOffset, memberAlignment);
2718 nextOffset = currentOffset + memberSize;
2719}
2720
David Netoa901ffe2016-06-08 14:11:40 +01002721void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002722{
David Netoa901ffe2016-06-08 14:11:40 +01002723 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2724 switch (glslangBuiltIn)
2725 {
2726 case glslang::EbvClipDistance:
2727 case glslang::EbvCullDistance:
2728 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002729#ifdef NV_EXTENSIONS
2730 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002731 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002732 case glslang::EbvViewportMaskNV:
2733 case glslang::EbvSecondaryPositionNV:
2734 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002735 case glslang::EbvPositionPerViewNV:
2736 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002737#endif
David Netoa901ffe2016-06-08 14:11:40 +01002738 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2739 // Alternately, we could just call this for any glslang built-in, since the
2740 // capability already guards against duplicates.
2741 TranslateBuiltInDecoration(glslangBuiltIn, false);
2742 break;
2743 default:
2744 // Capabilities were already generated when the struct was declared.
2745 break;
2746 }
John Kessenichebb50532016-05-16 19:22:05 -06002747}
2748
John Kessenich6fccb3c2016-09-19 16:01:41 -06002749bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002750{
John Kessenicheee9d532016-09-19 18:09:30 -06002751 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002752}
2753
2754// Make all the functions, skeletally, without actually visiting their bodies.
2755void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2756{
2757 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2758 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002759 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002760 continue;
2761
2762 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002763 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002764 //
qining25262b32016-05-06 17:25:16 -04002765 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002766 // function. What it is an address of varies:
2767 //
John Kessenich4bf71552016-09-02 11:20:21 -06002768 // - "in" parameters not marked as "const" can be written to without modifying the calling
2769 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002770 //
2771 // - "const in" parameters can just be the r-value, as no writes need occur.
2772 //
John Kessenich4bf71552016-09-02 11:20:21 -06002773 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2774 // 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 -06002775
2776 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002777 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002778 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2779
John Kessenich37789792017-03-21 23:56:40 -06002780 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName;
2781
John Kessenich140f3df2015-06-26 16:58:36 -06002782 for (int p = 0; p < (int)parameters.size(); ++p) {
2783 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2784 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002785 // can we pass by reference?
2786 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002787 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002788 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002789 (p == 0 && implicitThis)) // implicit 'this'
Jason Ekstranded15ef12016-06-08 13:54:48 -07002790 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2791 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002792 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2793 else
John Kessenich4bf71552016-09-02 11:20:21 -06002794 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002795 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002796 paramTypes.push_back(typeId);
2797 }
2798
2799 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002800 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2801 convertGlslangToSpvType(glslFunction->getType()),
2802 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002803 if (implicitThis)
2804 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002805
2806 // Track function to emit/call later
2807 functionMap[glslFunction->getName().c_str()] = function;
2808
2809 // Set the parameter id's
2810 for (int p = 0; p < (int)parameters.size(); ++p) {
2811 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2812 // give a name too
2813 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2814 }
2815 }
2816}
2817
2818// Process all the initializers, while skipping the functions and link objects
2819void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2820{
2821 builder.setBuildPoint(shaderEntry->getLastBlock());
2822 for (int i = 0; i < (int)initializers.size(); ++i) {
2823 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2824 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2825
2826 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002827 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002828 initializer->traverse(this);
2829 }
2830 }
2831}
2832
2833// Process all the functions, while skipping initializers.
2834void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2835{
2836 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2837 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002838 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002839 node->traverse(this);
2840 }
2841}
2842
2843void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2844{
qining25262b32016-05-06 17:25:16 -04002845 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002846 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002847 currentFunction = functionMap[node->getName().c_str()];
2848 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002849 builder.setBuildPoint(functionBlock);
2850}
2851
Rex Xu04db3f52015-09-16 11:44:02 +08002852void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002853{
Rex Xufc618912015-09-09 16:42:49 +08002854 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002855
2856 glslang::TSampler sampler = {};
2857 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002858 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002859 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2860 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2861 }
2862
John Kessenich140f3df2015-06-26 16:58:36 -06002863 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2864 builder.clearAccessChain();
2865 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002866
2867 // Special case l-value operands
2868 bool lvalue = false;
2869 switch (node.getOp()) {
2870 case glslang::EOpImageAtomicAdd:
2871 case glslang::EOpImageAtomicMin:
2872 case glslang::EOpImageAtomicMax:
2873 case glslang::EOpImageAtomicAnd:
2874 case glslang::EOpImageAtomicOr:
2875 case glslang::EOpImageAtomicXor:
2876 case glslang::EOpImageAtomicExchange:
2877 case glslang::EOpImageAtomicCompSwap:
2878 if (i == 0)
2879 lvalue = true;
2880 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002881 case glslang::EOpSparseImageLoad:
2882 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2883 lvalue = true;
2884 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002885 case glslang::EOpSparseTexture:
2886 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2887 lvalue = true;
2888 break;
2889 case glslang::EOpSparseTextureClamp:
2890 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2891 lvalue = true;
2892 break;
2893 case glslang::EOpSparseTextureLod:
2894 case glslang::EOpSparseTextureOffset:
2895 if (i == 3)
2896 lvalue = true;
2897 break;
2898 case glslang::EOpSparseTextureFetch:
2899 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2900 lvalue = true;
2901 break;
2902 case glslang::EOpSparseTextureFetchOffset:
2903 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2904 lvalue = true;
2905 break;
2906 case glslang::EOpSparseTextureLodOffset:
2907 case glslang::EOpSparseTextureGrad:
2908 case glslang::EOpSparseTextureOffsetClamp:
2909 if (i == 4)
2910 lvalue = true;
2911 break;
2912 case glslang::EOpSparseTextureGradOffset:
2913 case glslang::EOpSparseTextureGradClamp:
2914 if (i == 5)
2915 lvalue = true;
2916 break;
2917 case glslang::EOpSparseTextureGradOffsetClamp:
2918 if (i == 6)
2919 lvalue = true;
2920 break;
2921 case glslang::EOpSparseTextureGather:
2922 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2923 lvalue = true;
2924 break;
2925 case glslang::EOpSparseTextureGatherOffset:
2926 case glslang::EOpSparseTextureGatherOffsets:
2927 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2928 lvalue = true;
2929 break;
Rex Xufc618912015-09-09 16:42:49 +08002930 default:
2931 break;
2932 }
2933
Rex Xu6b86d492015-09-16 17:48:22 +08002934 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002935 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002936 else
John Kessenich32cfd492016-02-02 12:37:46 -07002937 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002938 }
2939}
2940
John Kessenichfc51d282015-08-19 13:34:18 -06002941void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002942{
John Kessenichfc51d282015-08-19 13:34:18 -06002943 builder.clearAccessChain();
2944 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002945 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002946}
John Kessenich140f3df2015-06-26 16:58:36 -06002947
John Kessenichfc51d282015-08-19 13:34:18 -06002948spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2949{
Rex Xufc618912015-09-09 16:42:49 +08002950 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002951 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002952 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002953 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002954
John Kessenichfc51d282015-08-19 13:34:18 -06002955 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002956 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2957 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2958 std::vector<spv::Id> arguments;
2959 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002960 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002961 else
2962 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002963 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002964
2965 spv::Builder::TextureParameters params = { };
2966 params.sampler = arguments[0];
2967
Rex Xu04db3f52015-09-16 11:44:02 +08002968 glslang::TCrackedTextureOp cracked;
2969 node->crackTexture(sampler, cracked);
2970
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002971 const bool isUnsignedResult =
2972 node->getType().getBasicType() == glslang::EbtUint64 ||
2973 node->getType().getBasicType() == glslang::EbtUint;
2974
John Kessenichfc51d282015-08-19 13:34:18 -06002975 // Check for queries
2976 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002977 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2978 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002979 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002980
John Kessenichfc51d282015-08-19 13:34:18 -06002981 switch (node->getOp()) {
2982 case glslang::EOpImageQuerySize:
2983 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002984 if (arguments.size() > 1) {
2985 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002986 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002987 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002988 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06002989 case glslang::EOpImageQuerySamples:
2990 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002991 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06002992 case glslang::EOpTextureQueryLod:
2993 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002994 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06002995 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002996 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08002997 case glslang::EOpSparseTexelsResident:
2998 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002999 default:
3000 assert(0);
3001 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003002 }
John Kessenich140f3df2015-06-26 16:58:36 -06003003 }
3004
Rex Xufc618912015-09-09 16:42:49 +08003005 // Check for image functions other than queries
3006 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003007 std::vector<spv::Id> operands;
3008 auto opIt = arguments.begin();
3009 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003010
3011 // Handle subpass operations
3012 // TODO: GLSL should change to have the "MS" only on the type rather than the
3013 // built-in function.
3014 if (cracked.subpass) {
3015 // add on the (0,0) coordinate
3016 spv::Id zero = builder.makeIntConstant(0);
3017 std::vector<spv::Id> comps;
3018 comps.push_back(zero);
3019 comps.push_back(zero);
3020 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3021 if (sampler.ms) {
3022 operands.push_back(spv::ImageOperandsSampleMask);
3023 operands.push_back(*(opIt++));
3024 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003025 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003026 }
3027
John Kessenich56bab042015-09-16 10:54:31 -06003028 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003029 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003030 if (sampler.ms) {
3031 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003032 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003033 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003034 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3035 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003036 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003037 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003038 if (sampler.ms) {
3039 operands.push_back(*(opIt + 1));
3040 operands.push_back(spv::ImageOperandsSampleMask);
3041 operands.push_back(*opIt);
3042 } else
3043 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003044 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003045 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3046 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003047 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003048 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3049 builder.addCapability(spv::CapabilitySparseResidency);
3050 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3051 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3052
3053 if (sampler.ms) {
3054 operands.push_back(spv::ImageOperandsSampleMask);
3055 operands.push_back(*opIt++);
3056 }
3057
3058 // Create the return type that was a special structure
3059 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003060 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003061 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3062 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3063
3064 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3065
3066 // Decode the return type
3067 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3068 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003069 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003070 // Process image atomic operations
3071
3072 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3073 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003074 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003075
John Kessenich8c8505c2016-07-26 12:50:38 -06003076 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003077 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003078
3079 std::vector<spv::Id> operands;
3080 operands.push_back(pointer);
3081 for (; opIt != arguments.end(); ++opIt)
3082 operands.push_back(*opIt);
3083
John Kessenich8c8505c2016-07-26 12:50:38 -06003084 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003085 }
3086 }
3087
3088 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003089 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003090 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3091
John Kessenichfc51d282015-08-19 13:34:18 -06003092 // check for bias argument
3093 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003094 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003095 int nonBiasArgCount = 2;
3096 if (cracked.offset)
3097 ++nonBiasArgCount;
3098 if (cracked.grad)
3099 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003100 if (cracked.lodClamp)
3101 ++nonBiasArgCount;
3102 if (sparse)
3103 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003104
3105 if ((int)arguments.size() > nonBiasArgCount)
3106 bias = true;
3107 }
3108
John Kessenicha5c33d62016-06-02 23:45:21 -06003109 // See if the sampler param should really be just the SPV image part
3110 if (cracked.fetch) {
3111 // a fetch needs to have the image extracted first
3112 if (builder.isSampledImage(params.sampler))
3113 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3114 }
3115
John Kessenichfc51d282015-08-19 13:34:18 -06003116 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003117
John Kessenichfc51d282015-08-19 13:34:18 -06003118 params.coords = arguments[1];
3119 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003120 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003121
3122 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003123 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003124 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003125 ++extraArgs;
3126 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003127 params.Dref = arguments[2];
3128 ++extraArgs;
3129 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003130 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003131 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003132 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003133 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003134 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003135 dRefComp = builder.getNumComponents(params.coords) - 1;
3136 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003137 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3138 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003139
3140 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003141 if (cracked.lod) {
3142 params.lod = arguments[2];
3143 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003144 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3145 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3146 noImplicitLod = true;
3147 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003148
3149 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003150 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003151 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003152 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003153 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003154
3155 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003156 if (cracked.grad) {
3157 params.gradX = arguments[2 + extraArgs];
3158 params.gradY = arguments[3 + extraArgs];
3159 extraArgs += 2;
3160 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003161
3162 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003163 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003164 params.offset = arguments[2 + extraArgs];
3165 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003166 } else if (cracked.offsets) {
3167 params.offsets = arguments[2 + extraArgs];
3168 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003169 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003170
3171 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003172 if (cracked.lodClamp) {
3173 params.lodClamp = arguments[2 + extraArgs];
3174 ++extraArgs;
3175 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003176
3177 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003178 if (sparse) {
3179 params.texelOut = arguments[2 + extraArgs];
3180 ++extraArgs;
3181 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003182
3183 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003184 if (bias) {
3185 params.bias = arguments[2 + extraArgs];
3186 ++extraArgs;
3187 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003188
3189 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003190 if (cracked.gather && ! sampler.shadow) {
3191 // default component is 0, if missing, otherwise an argument
3192 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003193 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003194 ++extraArgs;
3195 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003196 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003197 }
3198 }
John Kessenichfc51d282015-08-19 13:34:18 -06003199
John Kessenich65336482016-06-16 14:06:26 -06003200 // projective component (might not to move)
3201 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3202 // are divided by the last component of P."
3203 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3204 // unused components will appear after all used components."
3205 if (cracked.proj) {
3206 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3207 int projTargetComp;
3208 switch (sampler.dim) {
3209 case glslang::Esd1D: projTargetComp = 1; break;
3210 case glslang::Esd2D: projTargetComp = 2; break;
3211 case glslang::EsdRect: projTargetComp = 2; break;
3212 default: projTargetComp = projSourceComp; break;
3213 }
3214 // copy the projective coordinate if we have to
3215 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003216 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003217 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3218 projSourceComp);
3219 params.coords = builder.createCompositeInsert(projComp, params.coords,
3220 builder.getTypeId(params.coords), projTargetComp);
3221 }
3222 }
3223
John Kessenich8c8505c2016-07-26 12:50:38 -06003224 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003225}
3226
3227spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3228{
3229 // Grab the function's pointer from the previously created function
3230 spv::Function* function = functionMap[node->getName().c_str()];
3231 if (! function)
3232 return 0;
3233
3234 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3235 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3236
3237 // See comments in makeFunctions() for details about the semantics for parameter passing.
3238 //
3239 // These imply we need a four step process:
3240 // 1. Evaluate the arguments
3241 // 2. Allocate and make copies of in, out, and inout arguments
3242 // 3. Make the call
3243 // 4. Copy back the results
3244
3245 // 1. Evaluate the arguments
3246 std::vector<spv::Builder::AccessChain> lValues;
3247 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003248 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003249 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003250 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003251 // build l-value
3252 builder.clearAccessChain();
3253 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003254 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003255 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003256 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003257 // save l-value
3258 lValues.push_back(builder.getAccessChain());
3259 } else {
3260 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003261 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003262 }
3263 }
3264
3265 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3266 // copy the original into that space.
3267 //
3268 // Also, build up the list of actual arguments to pass in for the call
3269 int lValueCount = 0;
3270 int rValueCount = 0;
3271 std::vector<spv::Id> spvArgs;
3272 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003273 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003274 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003275 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003276 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3277 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003278 builder.setAccessChain(lValues[lValueCount]);
3279 arg = builder.accessChainGetLValue();
3280 ++lValueCount;
3281 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003282 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003283 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3284 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3285 // need to copy the input into output space
3286 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003287 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003288 builder.clearAccessChain();
3289 builder.setAccessChainLValue(arg);
3290 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003291 }
3292 ++lValueCount;
3293 } else {
3294 arg = rValues[rValueCount];
3295 ++rValueCount;
3296 }
3297 spvArgs.push_back(arg);
3298 }
3299
3300 // 3. Make the call.
3301 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003302 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003303
3304 // 4. Copy back out an "out" arguments.
3305 lValueCount = 0;
3306 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003307 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003308 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3309 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3310 spv::Id copy = builder.createLoad(spvArgs[a]);
3311 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003312 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003313 }
3314 ++lValueCount;
3315 }
3316 }
3317
3318 return result;
3319}
3320
3321// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003322spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3323 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003324 spv::Id typeId, spv::Id left, spv::Id right,
3325 glslang::TBasicType typeProxy, bool reduceComparison)
3326{
Rex Xu8ff43de2016-04-22 16:51:45 +08003327 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003328#ifdef AMD_EXTENSIONS
3329 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3330#else
John Kessenich140f3df2015-06-26 16:58:36 -06003331 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003332#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003333 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003334
3335 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003336 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003337 bool comparison = false;
3338
3339 switch (op) {
3340 case glslang::EOpAdd:
3341 case glslang::EOpAddAssign:
3342 if (isFloat)
3343 binOp = spv::OpFAdd;
3344 else
3345 binOp = spv::OpIAdd;
3346 break;
3347 case glslang::EOpSub:
3348 case glslang::EOpSubAssign:
3349 if (isFloat)
3350 binOp = spv::OpFSub;
3351 else
3352 binOp = spv::OpISub;
3353 break;
3354 case glslang::EOpMul:
3355 case glslang::EOpMulAssign:
3356 if (isFloat)
3357 binOp = spv::OpFMul;
3358 else
3359 binOp = spv::OpIMul;
3360 break;
3361 case glslang::EOpVectorTimesScalar:
3362 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003363 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003364 if (builder.isVector(right))
3365 std::swap(left, right);
3366 assert(builder.isScalar(right));
3367 needMatchingVectors = false;
3368 binOp = spv::OpVectorTimesScalar;
3369 } else
3370 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003371 break;
3372 case glslang::EOpVectorTimesMatrix:
3373 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003374 binOp = spv::OpVectorTimesMatrix;
3375 break;
3376 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003377 binOp = spv::OpMatrixTimesVector;
3378 break;
3379 case glslang::EOpMatrixTimesScalar:
3380 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003381 binOp = spv::OpMatrixTimesScalar;
3382 break;
3383 case glslang::EOpMatrixTimesMatrix:
3384 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003385 binOp = spv::OpMatrixTimesMatrix;
3386 break;
3387 case glslang::EOpOuterProduct:
3388 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003389 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003390 break;
3391
3392 case glslang::EOpDiv:
3393 case glslang::EOpDivAssign:
3394 if (isFloat)
3395 binOp = spv::OpFDiv;
3396 else if (isUnsigned)
3397 binOp = spv::OpUDiv;
3398 else
3399 binOp = spv::OpSDiv;
3400 break;
3401 case glslang::EOpMod:
3402 case glslang::EOpModAssign:
3403 if (isFloat)
3404 binOp = spv::OpFMod;
3405 else if (isUnsigned)
3406 binOp = spv::OpUMod;
3407 else
3408 binOp = spv::OpSMod;
3409 break;
3410 case glslang::EOpRightShift:
3411 case glslang::EOpRightShiftAssign:
3412 if (isUnsigned)
3413 binOp = spv::OpShiftRightLogical;
3414 else
3415 binOp = spv::OpShiftRightArithmetic;
3416 break;
3417 case glslang::EOpLeftShift:
3418 case glslang::EOpLeftShiftAssign:
3419 binOp = spv::OpShiftLeftLogical;
3420 break;
3421 case glslang::EOpAnd:
3422 case glslang::EOpAndAssign:
3423 binOp = spv::OpBitwiseAnd;
3424 break;
3425 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003426 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003427 binOp = spv::OpLogicalAnd;
3428 break;
3429 case glslang::EOpInclusiveOr:
3430 case glslang::EOpInclusiveOrAssign:
3431 binOp = spv::OpBitwiseOr;
3432 break;
3433 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003434 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003435 binOp = spv::OpLogicalOr;
3436 break;
3437 case glslang::EOpExclusiveOr:
3438 case glslang::EOpExclusiveOrAssign:
3439 binOp = spv::OpBitwiseXor;
3440 break;
3441 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003442 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003443 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003444 break;
3445
3446 case glslang::EOpLessThan:
3447 case glslang::EOpGreaterThan:
3448 case glslang::EOpLessThanEqual:
3449 case glslang::EOpGreaterThanEqual:
3450 case glslang::EOpEqual:
3451 case glslang::EOpNotEqual:
3452 case glslang::EOpVectorEqual:
3453 case glslang::EOpVectorNotEqual:
3454 comparison = true;
3455 break;
3456 default:
3457 break;
3458 }
3459
John Kessenich7c1aa102015-10-15 13:29:11 -06003460 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003461 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003462 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003463 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003464 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003465
3466 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003467 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003468 builder.promoteScalar(precision, left, right);
3469
qining25262b32016-05-06 17:25:16 -04003470 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3471 addDecoration(result, noContraction);
3472 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003473 }
3474
3475 if (! comparison)
3476 return 0;
3477
John Kessenich7c1aa102015-10-15 13:29:11 -06003478 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003479
John Kessenich4583b612016-08-07 19:14:22 -06003480 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3481 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003482 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003483
3484 switch (op) {
3485 case glslang::EOpLessThan:
3486 if (isFloat)
3487 binOp = spv::OpFOrdLessThan;
3488 else if (isUnsigned)
3489 binOp = spv::OpULessThan;
3490 else
3491 binOp = spv::OpSLessThan;
3492 break;
3493 case glslang::EOpGreaterThan:
3494 if (isFloat)
3495 binOp = spv::OpFOrdGreaterThan;
3496 else if (isUnsigned)
3497 binOp = spv::OpUGreaterThan;
3498 else
3499 binOp = spv::OpSGreaterThan;
3500 break;
3501 case glslang::EOpLessThanEqual:
3502 if (isFloat)
3503 binOp = spv::OpFOrdLessThanEqual;
3504 else if (isUnsigned)
3505 binOp = spv::OpULessThanEqual;
3506 else
3507 binOp = spv::OpSLessThanEqual;
3508 break;
3509 case glslang::EOpGreaterThanEqual:
3510 if (isFloat)
3511 binOp = spv::OpFOrdGreaterThanEqual;
3512 else if (isUnsigned)
3513 binOp = spv::OpUGreaterThanEqual;
3514 else
3515 binOp = spv::OpSGreaterThanEqual;
3516 break;
3517 case glslang::EOpEqual:
3518 case glslang::EOpVectorEqual:
3519 if (isFloat)
3520 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003521 else if (isBool)
3522 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003523 else
3524 binOp = spv::OpIEqual;
3525 break;
3526 case glslang::EOpNotEqual:
3527 case glslang::EOpVectorNotEqual:
3528 if (isFloat)
3529 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003530 else if (isBool)
3531 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003532 else
3533 binOp = spv::OpINotEqual;
3534 break;
3535 default:
3536 break;
3537 }
3538
qining25262b32016-05-06 17:25:16 -04003539 if (binOp != spv::OpNop) {
3540 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3541 addDecoration(result, noContraction);
3542 return builder.setPrecision(result, precision);
3543 }
John Kessenich140f3df2015-06-26 16:58:36 -06003544
3545 return 0;
3546}
3547
John Kessenich04bb8a02015-12-12 12:28:14 -07003548//
3549// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3550// These can be any of:
3551//
3552// matrix * scalar
3553// scalar * matrix
3554// matrix * matrix linear algebraic
3555// matrix * vector
3556// vector * matrix
3557// matrix * matrix componentwise
3558// matrix op matrix op in {+, -, /}
3559// matrix op scalar op in {+, -, /}
3560// scalar op matrix op in {+, -, /}
3561//
qining25262b32016-05-06 17:25:16 -04003562spv::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 -07003563{
3564 bool firstClass = true;
3565
3566 // First, handle first-class matrix operations (* and matrix/scalar)
3567 switch (op) {
3568 case spv::OpFDiv:
3569 if (builder.isMatrix(left) && builder.isScalar(right)) {
3570 // turn matrix / scalar into a multiply...
3571 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3572 op = spv::OpMatrixTimesScalar;
3573 } else
3574 firstClass = false;
3575 break;
3576 case spv::OpMatrixTimesScalar:
3577 if (builder.isMatrix(right))
3578 std::swap(left, right);
3579 assert(builder.isScalar(right));
3580 break;
3581 case spv::OpVectorTimesMatrix:
3582 assert(builder.isVector(left));
3583 assert(builder.isMatrix(right));
3584 break;
3585 case spv::OpMatrixTimesVector:
3586 assert(builder.isMatrix(left));
3587 assert(builder.isVector(right));
3588 break;
3589 case spv::OpMatrixTimesMatrix:
3590 assert(builder.isMatrix(left));
3591 assert(builder.isMatrix(right));
3592 break;
3593 default:
3594 firstClass = false;
3595 break;
3596 }
3597
qining25262b32016-05-06 17:25:16 -04003598 if (firstClass) {
3599 spv::Id result = builder.createBinOp(op, typeId, left, right);
3600 addDecoration(result, noContraction);
3601 return builder.setPrecision(result, precision);
3602 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003603
LoopDawg592860c2016-06-09 08:57:35 -06003604 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003605 // The result type of all of them is the same type as the (a) matrix operand.
3606 // The algorithm is to:
3607 // - break the matrix(es) into vectors
3608 // - smear any scalar to a vector
3609 // - do vector operations
3610 // - make a matrix out the vector results
3611 switch (op) {
3612 case spv::OpFAdd:
3613 case spv::OpFSub:
3614 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003615 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003616 case spv::OpFMul:
3617 {
3618 // one time set up...
3619 bool leftMat = builder.isMatrix(left);
3620 bool rightMat = builder.isMatrix(right);
3621 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3622 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3623 spv::Id scalarType = builder.getScalarTypeId(typeId);
3624 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3625 std::vector<spv::Id> results;
3626 spv::Id smearVec = spv::NoResult;
3627 if (builder.isScalar(left))
3628 smearVec = builder.smearScalar(precision, left, vecType);
3629 else if (builder.isScalar(right))
3630 smearVec = builder.smearScalar(precision, right, vecType);
3631
3632 // do each vector op
3633 for (unsigned int c = 0; c < numCols; ++c) {
3634 std::vector<unsigned int> indexes;
3635 indexes.push_back(c);
3636 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3637 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003638 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3639 addDecoration(result, noContraction);
3640 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003641 }
3642
3643 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003644 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003645 }
3646 default:
3647 assert(0);
3648 return spv::NoResult;
3649 }
3650}
3651
qining25262b32016-05-06 17:25:16 -04003652spv::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 -06003653{
3654 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003655 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003656 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003657 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003658#ifdef AMD_EXTENSIONS
3659 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3660#else
Rex Xu04db3f52015-09-16 11:44:02 +08003661 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003662#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003663
3664 switch (op) {
3665 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003666 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003667 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003668 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003669 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003670 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003671 unaryOp = spv::OpSNegate;
3672 break;
3673
3674 case glslang::EOpLogicalNot:
3675 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003676 unaryOp = spv::OpLogicalNot;
3677 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003678 case glslang::EOpBitwiseNot:
3679 unaryOp = spv::OpNot;
3680 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003681
John Kessenich140f3df2015-06-26 16:58:36 -06003682 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003683 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003684 break;
3685 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003686 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003687 break;
3688 case glslang::EOpTranspose:
3689 unaryOp = spv::OpTranspose;
3690 break;
3691
3692 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003693 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003694 break;
3695 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003696 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003697 break;
3698 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003699 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003700 break;
3701 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003702 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003703 break;
3704 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003705 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003706 break;
3707 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003708 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003709 break;
3710 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003711 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003712 break;
3713 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003714 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003715 break;
3716
3717 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003718 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003719 break;
3720 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003721 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003722 break;
3723 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003724 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003725 break;
3726 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003727 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003728 break;
3729 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003730 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003731 break;
3732 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003733 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003734 break;
3735
3736 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003737 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003738 break;
3739 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003740 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003741 break;
3742
3743 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003744 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003745 break;
3746 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003747 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003748 break;
3749 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003750 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003751 break;
3752 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003753 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003754 break;
3755 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003756 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003757 break;
3758 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003759 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003760 break;
3761
3762 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003763 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003764 break;
3765 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003766 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003767 break;
3768 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003769 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003770 break;
3771 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003772 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003773 break;
3774 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003775 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003776 break;
3777 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003778 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003779 break;
3780
3781 case glslang::EOpIsNan:
3782 unaryOp = spv::OpIsNan;
3783 break;
3784 case glslang::EOpIsInf:
3785 unaryOp = spv::OpIsInf;
3786 break;
LoopDawg592860c2016-06-09 08:57:35 -06003787 case glslang::EOpIsFinite:
3788 unaryOp = spv::OpIsFinite;
3789 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003790
Rex Xucbc426e2015-12-15 16:03:10 +08003791 case glslang::EOpFloatBitsToInt:
3792 case glslang::EOpFloatBitsToUint:
3793 case glslang::EOpIntBitsToFloat:
3794 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003795 case glslang::EOpDoubleBitsToInt64:
3796 case glslang::EOpDoubleBitsToUint64:
3797 case glslang::EOpInt64BitsToDouble:
3798 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003799 unaryOp = spv::OpBitcast;
3800 break;
3801
John Kessenich140f3df2015-06-26 16:58:36 -06003802 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003803 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003804 break;
3805 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003806 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003807 break;
3808 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003809 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003810 break;
3811 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003812 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003813 break;
3814 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003815 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003816 break;
3817 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003818 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003819 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003820 case glslang::EOpPackSnorm4x8:
3821 libCall = spv::GLSLstd450PackSnorm4x8;
3822 break;
3823 case glslang::EOpUnpackSnorm4x8:
3824 libCall = spv::GLSLstd450UnpackSnorm4x8;
3825 break;
3826 case glslang::EOpPackUnorm4x8:
3827 libCall = spv::GLSLstd450PackUnorm4x8;
3828 break;
3829 case glslang::EOpUnpackUnorm4x8:
3830 libCall = spv::GLSLstd450UnpackUnorm4x8;
3831 break;
3832 case glslang::EOpPackDouble2x32:
3833 libCall = spv::GLSLstd450PackDouble2x32;
3834 break;
3835 case glslang::EOpUnpackDouble2x32:
3836 libCall = spv::GLSLstd450UnpackDouble2x32;
3837 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003838
Rex Xu8ff43de2016-04-22 16:51:45 +08003839 case glslang::EOpPackInt2x32:
3840 case glslang::EOpUnpackInt2x32:
3841 case glslang::EOpPackUint2x32:
3842 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003843 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003844 break;
3845
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003846#ifdef AMD_EXTENSIONS
3847 case glslang::EOpPackFloat2x16:
3848 case glslang::EOpUnpackFloat2x16:
3849 unaryOp = spv::OpBitcast;
3850 break;
3851#endif
3852
John Kessenich140f3df2015-06-26 16:58:36 -06003853 case glslang::EOpDPdx:
3854 unaryOp = spv::OpDPdx;
3855 break;
3856 case glslang::EOpDPdy:
3857 unaryOp = spv::OpDPdy;
3858 break;
3859 case glslang::EOpFwidth:
3860 unaryOp = spv::OpFwidth;
3861 break;
3862 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003863 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003864 unaryOp = spv::OpDPdxFine;
3865 break;
3866 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003867 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003868 unaryOp = spv::OpDPdyFine;
3869 break;
3870 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003871 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003872 unaryOp = spv::OpFwidthFine;
3873 break;
3874 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003875 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003876 unaryOp = spv::OpDPdxCoarse;
3877 break;
3878 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003879 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003880 unaryOp = spv::OpDPdyCoarse;
3881 break;
3882 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003883 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003884 unaryOp = spv::OpFwidthCoarse;
3885 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003886 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003887 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003888 libCall = spv::GLSLstd450InterpolateAtCentroid;
3889 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003890 case glslang::EOpAny:
3891 unaryOp = spv::OpAny;
3892 break;
3893 case glslang::EOpAll:
3894 unaryOp = spv::OpAll;
3895 break;
3896
3897 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003898 if (isFloat)
3899 libCall = spv::GLSLstd450FAbs;
3900 else
3901 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003902 break;
3903 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003904 if (isFloat)
3905 libCall = spv::GLSLstd450FSign;
3906 else
3907 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003908 break;
3909
John Kessenichfc51d282015-08-19 13:34:18 -06003910 case glslang::EOpAtomicCounterIncrement:
3911 case glslang::EOpAtomicCounterDecrement:
3912 case glslang::EOpAtomicCounter:
3913 {
3914 // Handle all of the atomics in one place, in createAtomicOperation()
3915 std::vector<spv::Id> operands;
3916 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003917 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003918 }
3919
John Kessenichfc51d282015-08-19 13:34:18 -06003920 case glslang::EOpBitFieldReverse:
3921 unaryOp = spv::OpBitReverse;
3922 break;
3923 case glslang::EOpBitCount:
3924 unaryOp = spv::OpBitCount;
3925 break;
3926 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003927 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003928 break;
3929 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003930 if (isUnsigned)
3931 libCall = spv::GLSLstd450FindUMsb;
3932 else
3933 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003934 break;
3935
Rex Xu574ab042016-04-14 16:53:07 +08003936 case glslang::EOpBallot:
3937 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003938 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003939 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003940 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003941#ifdef AMD_EXTENSIONS
3942 case glslang::EOpMinInvocations:
3943 case glslang::EOpMaxInvocations:
3944 case glslang::EOpAddInvocations:
3945 case glslang::EOpMinInvocationsNonUniform:
3946 case glslang::EOpMaxInvocationsNonUniform:
3947 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08003948 case glslang::EOpMinInvocationsInclusiveScan:
3949 case glslang::EOpMaxInvocationsInclusiveScan:
3950 case glslang::EOpAddInvocationsInclusiveScan:
3951 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
3952 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
3953 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
3954 case glslang::EOpMinInvocationsExclusiveScan:
3955 case glslang::EOpMaxInvocationsExclusiveScan:
3956 case glslang::EOpAddInvocationsExclusiveScan:
3957 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
3958 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
3959 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08003960#endif
Rex Xu51596642016-09-21 18:56:12 +08003961 {
3962 std::vector<spv::Id> operands;
3963 operands.push_back(operand);
3964 return createInvocationsOperation(op, typeId, operands, typeProxy);
3965 }
Rex Xu9d93a232016-05-05 12:30:44 +08003966
3967#ifdef AMD_EXTENSIONS
3968 case glslang::EOpMbcnt:
3969 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3970 libCall = spv::MbcntAMD;
3971 break;
3972
3973 case glslang::EOpCubeFaceIndex:
3974 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3975 libCall = spv::CubeFaceIndexAMD;
3976 break;
3977
3978 case glslang::EOpCubeFaceCoord:
3979 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3980 libCall = spv::CubeFaceCoordAMD;
3981 break;
3982#endif
Rex Xu338b1852016-05-05 20:38:33 +08003983
John Kessenich140f3df2015-06-26 16:58:36 -06003984 default:
3985 return 0;
3986 }
3987
3988 spv::Id id;
3989 if (libCall >= 0) {
3990 std::vector<spv::Id> args;
3991 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003992 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003993 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003994 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003995 }
John Kessenich140f3df2015-06-26 16:58:36 -06003996
qining25262b32016-05-06 17:25:16 -04003997 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003998 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003999}
4000
John Kessenich7a53f762016-01-20 11:19:27 -07004001// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004002spv::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 -07004003{
4004 // Handle unary operations vector by vector.
4005 // The result type is the same type as the original type.
4006 // The algorithm is to:
4007 // - break the matrix into vectors
4008 // - apply the operation to each vector
4009 // - make a matrix out the vector results
4010
4011 // get the types sorted out
4012 int numCols = builder.getNumColumns(operand);
4013 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004014 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4015 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004016 std::vector<spv::Id> results;
4017
4018 // do each vector op
4019 for (int c = 0; c < numCols; ++c) {
4020 std::vector<unsigned int> indexes;
4021 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004022 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4023 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4024 addDecoration(destVec, noContraction);
4025 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004026 }
4027
4028 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004029 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004030}
4031
Rex Xu73e3ce72016-04-27 18:48:17 +08004032spv::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 -06004033{
4034 spv::Op convOp = spv::OpNop;
4035 spv::Id zero = 0;
4036 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004037 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004038
4039 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4040
4041 switch (op) {
4042 case glslang::EOpConvIntToBool:
4043 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004044 case glslang::EOpConvInt64ToBool:
4045 case glslang::EOpConvUint64ToBool:
4046 zero = (op == glslang::EOpConvInt64ToBool ||
4047 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004048 zero = makeSmearedConstant(zero, vectorSize);
4049 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4050
4051 case glslang::EOpConvFloatToBool:
4052 zero = builder.makeFloatConstant(0.0F);
4053 zero = makeSmearedConstant(zero, vectorSize);
4054 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4055
4056 case glslang::EOpConvDoubleToBool:
4057 zero = builder.makeDoubleConstant(0.0);
4058 zero = makeSmearedConstant(zero, vectorSize);
4059 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4060
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004061#ifdef AMD_EXTENSIONS
4062 case glslang::EOpConvFloat16ToBool:
4063 zero = builder.makeFloat16Constant(0.0F);
4064 zero = makeSmearedConstant(zero, vectorSize);
4065 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4066#endif
4067
John Kessenich140f3df2015-06-26 16:58:36 -06004068 case glslang::EOpConvBoolToFloat:
4069 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004070 zero = builder.makeFloatConstant(0.0F);
4071 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004072 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004073
John Kessenich140f3df2015-06-26 16:58:36 -06004074 case glslang::EOpConvBoolToDouble:
4075 convOp = spv::OpSelect;
4076 zero = builder.makeDoubleConstant(0.0);
4077 one = builder.makeDoubleConstant(1.0);
4078 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004079
4080#ifdef AMD_EXTENSIONS
4081 case glslang::EOpConvBoolToFloat16:
4082 convOp = spv::OpSelect;
4083 zero = builder.makeFloat16Constant(0.0F);
4084 one = builder.makeFloat16Constant(1.0F);
4085 break;
4086#endif
4087
John Kessenich140f3df2015-06-26 16:58:36 -06004088 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004089 case glslang::EOpConvBoolToInt64:
4090 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4091 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004092 convOp = spv::OpSelect;
4093 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004094
John Kessenich140f3df2015-06-26 16:58:36 -06004095 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004096 case glslang::EOpConvBoolToUint64:
4097 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4098 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004099 convOp = spv::OpSelect;
4100 break;
4101
4102 case glslang::EOpConvIntToFloat:
4103 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004104 case glslang::EOpConvInt64ToFloat:
4105 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004106#ifdef AMD_EXTENSIONS
4107 case glslang::EOpConvIntToFloat16:
4108 case glslang::EOpConvInt64ToFloat16:
4109#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004110 convOp = spv::OpConvertSToF;
4111 break;
4112
4113 case glslang::EOpConvUintToFloat:
4114 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004115 case glslang::EOpConvUint64ToFloat:
4116 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004117#ifdef AMD_EXTENSIONS
4118 case glslang::EOpConvUintToFloat16:
4119 case glslang::EOpConvUint64ToFloat16:
4120#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004121 convOp = spv::OpConvertUToF;
4122 break;
4123
4124 case glslang::EOpConvDoubleToFloat:
4125 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004126#ifdef AMD_EXTENSIONS
4127 case glslang::EOpConvDoubleToFloat16:
4128 case glslang::EOpConvFloat16ToDouble:
4129 case glslang::EOpConvFloatToFloat16:
4130 case glslang::EOpConvFloat16ToFloat:
4131#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004132 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004133 if (builder.isMatrixType(destType))
4134 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004135 break;
4136
4137 case glslang::EOpConvFloatToInt:
4138 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004139 case glslang::EOpConvFloatToInt64:
4140 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004141#ifdef AMD_EXTENSIONS
4142 case glslang::EOpConvFloat16ToInt:
4143 case glslang::EOpConvFloat16ToInt64:
4144#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004145 convOp = spv::OpConvertFToS;
4146 break;
4147
4148 case glslang::EOpConvUintToInt:
4149 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004150 case glslang::EOpConvUint64ToInt64:
4151 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004152 if (builder.isInSpecConstCodeGenMode()) {
4153 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004154 zero = (op == glslang::EOpConvUint64ToInt64 ||
4155 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004156 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004157 // Use OpIAdd, instead of OpBitcast to do the conversion when
4158 // generating for OpSpecConstantOp instruction.
4159 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4160 }
4161 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004162 convOp = spv::OpBitcast;
4163 break;
4164
4165 case glslang::EOpConvFloatToUint:
4166 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004167 case glslang::EOpConvFloatToUint64:
4168 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004169#ifdef AMD_EXTENSIONS
4170 case glslang::EOpConvFloat16ToUint:
4171 case glslang::EOpConvFloat16ToUint64:
4172#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004173 convOp = spv::OpConvertFToU;
4174 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004175
4176 case glslang::EOpConvIntToInt64:
4177 case glslang::EOpConvInt64ToInt:
4178 convOp = spv::OpSConvert;
4179 break;
4180
4181 case glslang::EOpConvUintToUint64:
4182 case glslang::EOpConvUint64ToUint:
4183 convOp = spv::OpUConvert;
4184 break;
4185
4186 case glslang::EOpConvIntToUint64:
4187 case glslang::EOpConvInt64ToUint:
4188 case glslang::EOpConvUint64ToInt:
4189 case glslang::EOpConvUintToInt64:
4190 // OpSConvert/OpUConvert + OpBitCast
4191 switch (op) {
4192 case glslang::EOpConvIntToUint64:
4193 convOp = spv::OpSConvert;
4194 type = builder.makeIntType(64);
4195 break;
4196 case glslang::EOpConvInt64ToUint:
4197 convOp = spv::OpSConvert;
4198 type = builder.makeIntType(32);
4199 break;
4200 case glslang::EOpConvUint64ToInt:
4201 convOp = spv::OpUConvert;
4202 type = builder.makeUintType(32);
4203 break;
4204 case glslang::EOpConvUintToInt64:
4205 convOp = spv::OpUConvert;
4206 type = builder.makeUintType(64);
4207 break;
4208 default:
4209 assert(0);
4210 break;
4211 }
4212
4213 if (vectorSize > 0)
4214 type = builder.makeVectorType(type, vectorSize);
4215
4216 operand = builder.createUnaryOp(convOp, type, operand);
4217
4218 if (builder.isInSpecConstCodeGenMode()) {
4219 // Build zero scalar or vector for OpIAdd.
4220 zero = (op == glslang::EOpConvIntToUint64 ||
4221 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4222 zero = makeSmearedConstant(zero, vectorSize);
4223 // Use OpIAdd, instead of OpBitcast to do the conversion when
4224 // generating for OpSpecConstantOp instruction.
4225 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4226 }
4227 // For normal run-time conversion instruction, use OpBitcast.
4228 convOp = spv::OpBitcast;
4229 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004230 default:
4231 break;
4232 }
4233
4234 spv::Id result = 0;
4235 if (convOp == spv::OpNop)
4236 return result;
4237
4238 if (convOp == spv::OpSelect) {
4239 zero = makeSmearedConstant(zero, vectorSize);
4240 one = makeSmearedConstant(one, vectorSize);
4241 result = builder.createTriOp(convOp, destType, operand, one, zero);
4242 } else
4243 result = builder.createUnaryOp(convOp, destType, operand);
4244
John Kessenich32cfd492016-02-02 12:37:46 -07004245 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004246}
4247
4248spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4249{
4250 if (vectorSize == 0)
4251 return constant;
4252
4253 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4254 std::vector<spv::Id> components;
4255 for (int c = 0; c < vectorSize; ++c)
4256 components.push_back(constant);
4257 return builder.makeCompositeConstant(vectorTypeId, components);
4258}
4259
John Kessenich426394d2015-07-23 10:22:48 -06004260// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004261spv::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 -06004262{
4263 spv::Op opCode = spv::OpNop;
4264
4265 switch (op) {
4266 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004267 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004268 opCode = spv::OpAtomicIAdd;
4269 break;
4270 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004271 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004272 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004273 break;
4274 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004275 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004276 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004277 break;
4278 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004279 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004280 opCode = spv::OpAtomicAnd;
4281 break;
4282 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004283 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004284 opCode = spv::OpAtomicOr;
4285 break;
4286 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004287 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004288 opCode = spv::OpAtomicXor;
4289 break;
4290 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004291 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004292 opCode = spv::OpAtomicExchange;
4293 break;
4294 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004295 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004296 opCode = spv::OpAtomicCompareExchange;
4297 break;
4298 case glslang::EOpAtomicCounterIncrement:
4299 opCode = spv::OpAtomicIIncrement;
4300 break;
4301 case glslang::EOpAtomicCounterDecrement:
4302 opCode = spv::OpAtomicIDecrement;
4303 break;
4304 case glslang::EOpAtomicCounter:
4305 opCode = spv::OpAtomicLoad;
4306 break;
4307 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004308 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004309 break;
4310 }
4311
4312 // Sort out the operands
4313 // - mapping from glslang -> SPV
4314 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004315 // - compare-exchange swaps the value and comparator
4316 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004317 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4318 auto opIt = operands.begin(); // walk the glslang operands
4319 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004320 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4321 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4322 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004323 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4324 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004325 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004326 spvAtomicOperands.push_back(*(opIt + 1));
4327 spvAtomicOperands.push_back(*opIt);
4328 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004329 }
John Kessenich426394d2015-07-23 10:22:48 -06004330
John Kessenich3e60a6f2015-09-14 22:45:16 -06004331 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004332 for (; opIt != operands.end(); ++opIt)
4333 spvAtomicOperands.push_back(*opIt);
4334
4335 return builder.createOp(opCode, typeId, spvAtomicOperands);
4336}
4337
John Kessenich91cef522016-05-05 16:45:40 -06004338// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004339spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004340{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004341#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004342 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004343 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004344#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004345
Rex Xu51596642016-09-21 18:56:12 +08004346 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004347 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004348 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4349
chaocf200da82016-12-20 12:44:35 -08004350 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4351 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004352 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4353 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004354 } else if (op == glslang::EOpAnyInvocation ||
4355 op == glslang::EOpAllInvocations ||
4356 op == glslang::EOpAllInvocationsEqual) {
4357 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4358 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004359 } else {
4360 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004361#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004362 if (op == glslang::EOpMinInvocationsNonUniform ||
4363 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004364 op == glslang::EOpAddInvocationsNonUniform ||
4365 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4366 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4367 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4368 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4369 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4370 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004371 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004372#endif
Rex Xu51596642016-09-21 18:56:12 +08004373
4374 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004375#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004376 switch (op) {
4377 case glslang::EOpMinInvocations:
4378 case glslang::EOpMaxInvocations:
4379 case glslang::EOpAddInvocations:
4380 case glslang::EOpMinInvocationsNonUniform:
4381 case glslang::EOpMaxInvocationsNonUniform:
4382 case glslang::EOpAddInvocationsNonUniform:
4383 groupOperation = spv::GroupOperationReduce;
4384 spvGroupOperands.push_back(groupOperation);
4385 break;
4386 case glslang::EOpMinInvocationsInclusiveScan:
4387 case glslang::EOpMaxInvocationsInclusiveScan:
4388 case glslang::EOpAddInvocationsInclusiveScan:
4389 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4390 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4391 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4392 groupOperation = spv::GroupOperationInclusiveScan;
4393 spvGroupOperands.push_back(groupOperation);
4394 break;
4395 case glslang::EOpMinInvocationsExclusiveScan:
4396 case glslang::EOpMaxInvocationsExclusiveScan:
4397 case glslang::EOpAddInvocationsExclusiveScan:
4398 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4399 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4400 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4401 groupOperation = spv::GroupOperationExclusiveScan;
4402 spvGroupOperands.push_back(groupOperation);
4403 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004404 default:
4405 break;
Rex Xu430ef402016-10-14 17:22:23 +08004406 }
Rex Xu9d93a232016-05-05 12:30:44 +08004407#endif
Rex Xu51596642016-09-21 18:56:12 +08004408 }
4409
4410 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4411 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004412
4413 switch (op) {
4414 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004415 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004416 break;
John Kessenich91cef522016-05-05 16:45:40 -06004417 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004418 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004419 break;
John Kessenich91cef522016-05-05 16:45:40 -06004420 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004421 opCode = spv::OpSubgroupAllEqualKHR;
4422 break;
Rex Xu51596642016-09-21 18:56:12 +08004423 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004424 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004425 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004426 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004427 break;
4428 case glslang::EOpReadFirstInvocation:
4429 opCode = spv::OpSubgroupFirstInvocationKHR;
4430 break;
4431 case glslang::EOpBallot:
4432 {
4433 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4434 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4435 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4436 //
4437 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4438 //
4439 spv::Id uintType = builder.makeUintType(32);
4440 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4441 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4442
4443 std::vector<spv::Id> components;
4444 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4445 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4446
4447 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4448 return builder.createUnaryOp(spv::OpBitcast, typeId,
4449 builder.createCompositeConstruct(uvec2Type, components));
4450 }
4451
Rex Xu9d93a232016-05-05 12:30:44 +08004452#ifdef AMD_EXTENSIONS
4453 case glslang::EOpMinInvocations:
4454 case glslang::EOpMaxInvocations:
4455 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004456 case glslang::EOpMinInvocationsInclusiveScan:
4457 case glslang::EOpMaxInvocationsInclusiveScan:
4458 case glslang::EOpAddInvocationsInclusiveScan:
4459 case glslang::EOpMinInvocationsExclusiveScan:
4460 case glslang::EOpMaxInvocationsExclusiveScan:
4461 case glslang::EOpAddInvocationsExclusiveScan:
4462 if (op == glslang::EOpMinInvocations ||
4463 op == glslang::EOpMinInvocationsInclusiveScan ||
4464 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004465 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004466 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004467 else {
4468 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004469 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004470 else
Rex Xu51596642016-09-21 18:56:12 +08004471 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004472 }
Rex Xu430ef402016-10-14 17:22:23 +08004473 } else if (op == glslang::EOpMaxInvocations ||
4474 op == glslang::EOpMaxInvocationsInclusiveScan ||
4475 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004476 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004477 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004478 else {
4479 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004480 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004481 else
Rex Xu51596642016-09-21 18:56:12 +08004482 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004483 }
4484 } else {
4485 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004486 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004487 else
Rex Xu51596642016-09-21 18:56:12 +08004488 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004489 }
4490
Rex Xu2bbbe062016-08-23 15:41:05 +08004491 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004492 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004493
4494 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004495 case glslang::EOpMinInvocationsNonUniform:
4496 case glslang::EOpMaxInvocationsNonUniform:
4497 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004498 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4499 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4500 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4501 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4502 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4503 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4504 if (op == glslang::EOpMinInvocationsNonUniform ||
4505 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4506 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004507 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004508 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004509 else {
4510 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004511 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004512 else
Rex Xu51596642016-09-21 18:56:12 +08004513 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004514 }
4515 }
Rex Xu430ef402016-10-14 17:22:23 +08004516 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4517 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4518 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004519 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004520 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004521 else {
4522 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004523 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004524 else
Rex Xu51596642016-09-21 18:56:12 +08004525 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004526 }
4527 }
4528 else {
4529 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004530 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004531 else
Rex Xu51596642016-09-21 18:56:12 +08004532 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004533 }
4534
Rex Xu2bbbe062016-08-23 15:41:05 +08004535 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004536 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004537
4538 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004539#endif
John Kessenich91cef522016-05-05 16:45:40 -06004540 default:
4541 logger->missingFunctionality("invocation operation");
4542 return spv::NoResult;
4543 }
Rex Xu51596642016-09-21 18:56:12 +08004544
4545 assert(opCode != spv::OpNop);
4546 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004547}
4548
Rex Xu2bbbe062016-08-23 15:41:05 +08004549// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004550spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004551{
Rex Xub7072052016-09-26 15:53:40 +08004552#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004553 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4554 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004555 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004556 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004557 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4558 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4559 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004560#else
4561 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4562 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004563 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4564 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004565#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004566
4567 // Handle group invocation operations scalar by scalar.
4568 // The result type is the same type as the original type.
4569 // The algorithm is to:
4570 // - break the vector into scalars
4571 // - apply the operation to each scalar
4572 // - make a vector out the scalar results
4573
4574 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004575 int numComponents = builder.getNumComponents(operands[0]);
4576 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004577 std::vector<spv::Id> results;
4578
4579 // do each scalar op
4580 for (int comp = 0; comp < numComponents; ++comp) {
4581 std::vector<unsigned int> indexes;
4582 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004583 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004584 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004585 if (op == spv::OpSubgroupReadInvocationKHR) {
4586 spvGroupOperands.push_back(scalar);
4587 spvGroupOperands.push_back(operands[1]);
4588 } else if (op == spv::OpGroupBroadcast) {
4589 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004590 spvGroupOperands.push_back(scalar);
4591 spvGroupOperands.push_back(operands[1]);
4592 } else {
chaocf200da82016-12-20 12:44:35 -08004593 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004594 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004595 spvGroupOperands.push_back(scalar);
4596 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004597
Rex Xub7072052016-09-26 15:53:40 +08004598 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004599 }
4600
4601 // put the pieces together
4602 return builder.createCompositeConstruct(typeId, results);
4603}
Rex Xu2bbbe062016-08-23 15:41:05 +08004604
John Kessenich5e4b1242015-08-06 22:53:06 -06004605spv::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 -06004606{
Rex Xu8ff43de2016-04-22 16:51:45 +08004607 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004608#ifdef AMD_EXTENSIONS
4609 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4610#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004611 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004612#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004613
John Kessenich140f3df2015-06-26 16:58:36 -06004614 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004615 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004616 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004617 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004618 spv::Id typeId0 = 0;
4619 if (consumedOperands > 0)
4620 typeId0 = builder.getTypeId(operands[0]);
4621 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004622
4623 switch (op) {
4624 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004625 if (isFloat)
4626 libCall = spv::GLSLstd450FMin;
4627 else if (isUnsigned)
4628 libCall = spv::GLSLstd450UMin;
4629 else
4630 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004631 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004632 break;
4633 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004634 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004635 break;
4636 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004637 if (isFloat)
4638 libCall = spv::GLSLstd450FMax;
4639 else if (isUnsigned)
4640 libCall = spv::GLSLstd450UMax;
4641 else
4642 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004643 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004644 break;
4645 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004646 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004647 break;
4648 case glslang::EOpDot:
4649 opCode = spv::OpDot;
4650 break;
4651 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004652 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004653 break;
4654
4655 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004656 if (isFloat)
4657 libCall = spv::GLSLstd450FClamp;
4658 else if (isUnsigned)
4659 libCall = spv::GLSLstd450UClamp;
4660 else
4661 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004662 builder.promoteScalar(precision, operands.front(), operands[1]);
4663 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004664 break;
4665 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004666 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4667 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004668 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004669 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004670 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004671 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004672 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004673 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004674 break;
4675 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004676 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004677 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004678 break;
4679 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004680 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004681 builder.promoteScalar(precision, operands[0], operands[2]);
4682 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004683 break;
4684
4685 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004686 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004687 break;
4688 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004689 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004690 break;
4691 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004692 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004693 break;
4694 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004695 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004696 break;
4697 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004698 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004699 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004700 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004701 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004702 libCall = spv::GLSLstd450InterpolateAtSample;
4703 break;
4704 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004705 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004706 libCall = spv::GLSLstd450InterpolateAtOffset;
4707 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004708 case glslang::EOpAddCarry:
4709 opCode = spv::OpIAddCarry;
4710 typeId = builder.makeStructResultType(typeId0, typeId0);
4711 consumedOperands = 2;
4712 break;
4713 case glslang::EOpSubBorrow:
4714 opCode = spv::OpISubBorrow;
4715 typeId = builder.makeStructResultType(typeId0, typeId0);
4716 consumedOperands = 2;
4717 break;
4718 case glslang::EOpUMulExtended:
4719 opCode = spv::OpUMulExtended;
4720 typeId = builder.makeStructResultType(typeId0, typeId0);
4721 consumedOperands = 2;
4722 break;
4723 case glslang::EOpIMulExtended:
4724 opCode = spv::OpSMulExtended;
4725 typeId = builder.makeStructResultType(typeId0, typeId0);
4726 consumedOperands = 2;
4727 break;
4728 case glslang::EOpBitfieldExtract:
4729 if (isUnsigned)
4730 opCode = spv::OpBitFieldUExtract;
4731 else
4732 opCode = spv::OpBitFieldSExtract;
4733 break;
4734 case glslang::EOpBitfieldInsert:
4735 opCode = spv::OpBitFieldInsert;
4736 break;
4737
4738 case glslang::EOpFma:
4739 libCall = spv::GLSLstd450Fma;
4740 break;
4741 case glslang::EOpFrexp:
4742 libCall = spv::GLSLstd450FrexpStruct;
4743 if (builder.getNumComponents(operands[0]) == 1)
4744 frexpIntType = builder.makeIntegerType(32, true);
4745 else
4746 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4747 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4748 consumedOperands = 1;
4749 break;
4750 case glslang::EOpLdexp:
4751 libCall = spv::GLSLstd450Ldexp;
4752 break;
4753
Rex Xu574ab042016-04-14 16:53:07 +08004754 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004755 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004756
Rex Xu9d93a232016-05-05 12:30:44 +08004757#ifdef AMD_EXTENSIONS
4758 case glslang::EOpSwizzleInvocations:
4759 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4760 libCall = spv::SwizzleInvocationsAMD;
4761 break;
4762 case glslang::EOpSwizzleInvocationsMasked:
4763 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4764 libCall = spv::SwizzleInvocationsMaskedAMD;
4765 break;
4766 case glslang::EOpWriteInvocation:
4767 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4768 libCall = spv::WriteInvocationAMD;
4769 break;
4770
4771 case glslang::EOpMin3:
4772 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4773 if (isFloat)
4774 libCall = spv::FMin3AMD;
4775 else {
4776 if (isUnsigned)
4777 libCall = spv::UMin3AMD;
4778 else
4779 libCall = spv::SMin3AMD;
4780 }
4781 break;
4782 case glslang::EOpMax3:
4783 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4784 if (isFloat)
4785 libCall = spv::FMax3AMD;
4786 else {
4787 if (isUnsigned)
4788 libCall = spv::UMax3AMD;
4789 else
4790 libCall = spv::SMax3AMD;
4791 }
4792 break;
4793 case glslang::EOpMid3:
4794 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4795 if (isFloat)
4796 libCall = spv::FMid3AMD;
4797 else {
4798 if (isUnsigned)
4799 libCall = spv::UMid3AMD;
4800 else
4801 libCall = spv::SMid3AMD;
4802 }
4803 break;
4804
4805 case glslang::EOpInterpolateAtVertex:
4806 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4807 libCall = spv::InterpolateAtVertexAMD;
4808 break;
4809#endif
4810
John Kessenich140f3df2015-06-26 16:58:36 -06004811 default:
4812 return 0;
4813 }
4814
4815 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004816 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004817 // Use an extended instruction from the standard library.
4818 // Construct the call arguments, without modifying the original operands vector.
4819 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4820 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004821 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004822 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004823 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004824 case 0:
4825 // should all be handled by visitAggregate and createNoArgOperation
4826 assert(0);
4827 return 0;
4828 case 1:
4829 // should all be handled by createUnaryOperation
4830 assert(0);
4831 return 0;
4832 case 2:
4833 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4834 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004835 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004836 // anything 3 or over doesn't have l-value operands, so all should be consumed
4837 assert(consumedOperands == operands.size());
4838 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004839 break;
4840 }
4841 }
4842
John Kessenich55e7d112015-11-15 21:33:39 -07004843 // Decode the return types that were structures
4844 switch (op) {
4845 case glslang::EOpAddCarry:
4846 case glslang::EOpSubBorrow:
4847 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4848 id = builder.createCompositeExtract(id, typeId0, 0);
4849 break;
4850 case glslang::EOpUMulExtended:
4851 case glslang::EOpIMulExtended:
4852 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4853 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4854 break;
4855 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004856 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004857 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4858 id = builder.createCompositeExtract(id, typeId0, 0);
4859 break;
4860 default:
4861 break;
4862 }
4863
John Kessenich32cfd492016-02-02 12:37:46 -07004864 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004865}
4866
Rex Xu9d93a232016-05-05 12:30:44 +08004867// Intrinsics with no arguments (or no return value, and no precision).
4868spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004869{
4870 // TODO: get the barrier operands correct
4871
4872 switch (op) {
4873 case glslang::EOpEmitVertex:
4874 builder.createNoResultOp(spv::OpEmitVertex);
4875 return 0;
4876 case glslang::EOpEndPrimitive:
4877 builder.createNoResultOp(spv::OpEndPrimitive);
4878 return 0;
4879 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004880 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004881 return 0;
4882 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004883 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004884 return 0;
4885 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004886 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004887 return 0;
4888 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004889 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004890 return 0;
4891 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004892 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004893 return 0;
4894 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004895 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004896 return 0;
4897 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004898 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004899 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004900 case glslang::EOpAllMemoryBarrierWithGroupSync:
4901 // Control barrier with non-"None" semantic is also a memory barrier.
4902 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4903 return 0;
4904 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4905 // Control barrier with non-"None" semantic is also a memory barrier.
4906 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4907 return 0;
4908 case glslang::EOpWorkgroupMemoryBarrier:
4909 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4910 return 0;
4911 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4912 // Control barrier with non-"None" semantic is also a memory barrier.
4913 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4914 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004915#ifdef AMD_EXTENSIONS
4916 case glslang::EOpTime:
4917 {
4918 std::vector<spv::Id> args; // Dummy arguments
4919 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4920 return builder.setPrecision(id, precision);
4921 }
4922#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004923 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004924 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004925 return 0;
4926 }
4927}
4928
4929spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4930{
John Kessenich2f273362015-07-18 22:34:27 -06004931 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004932 spv::Id id;
4933 if (symbolValues.end() != iter) {
4934 id = iter->second;
4935 return id;
4936 }
4937
4938 // it was not found, create it
4939 id = createSpvVariable(symbol);
4940 symbolValues[symbol->getId()] = id;
4941
Rex Xuc884b4a2016-06-29 15:03:44 +08004942 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004943 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004944 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004945 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004946 if (symbol->getType().getQualifier().hasSpecConstantId())
4947 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004948 if (symbol->getQualifier().hasIndex())
4949 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4950 if (symbol->getQualifier().hasComponent())
4951 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4952 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004953 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004954 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004955 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004956 if (symbol->getQualifier().hasXfbBuffer())
4957 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4958 if (symbol->getQualifier().hasXfbOffset())
4959 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4960 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004961 // atomic counters use this:
4962 if (symbol->getQualifier().hasOffset())
4963 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004964 }
4965
scygan2c864272016-05-18 18:09:17 +02004966 if (symbol->getQualifier().hasLocation())
4967 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004968 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004969 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004970 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004971 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004972 }
John Kessenich140f3df2015-06-26 16:58:36 -06004973 if (symbol->getQualifier().hasSet())
4974 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004975 else if (IsDescriptorResource(symbol->getType())) {
4976 // default to 0
4977 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4978 }
John Kessenich140f3df2015-06-26 16:58:36 -06004979 if (symbol->getQualifier().hasBinding())
4980 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004981 if (symbol->getQualifier().hasAttachment())
4982 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004983 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004984 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004985 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004986 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004987 if (symbol->getQualifier().hasXfbBuffer())
4988 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4989 }
4990
Rex Xu1da878f2016-02-21 20:59:01 +08004991 if (symbol->getType().isImage()) {
4992 std::vector<spv::Decoration> memory;
4993 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4994 for (unsigned int i = 0; i < memory.size(); ++i)
4995 addDecoration(id, memory[i]);
4996 }
4997
John Kessenich140f3df2015-06-26 16:58:36 -06004998 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004999 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005000 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005001 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005002
John Kessenichecba76f2017-01-06 00:34:48 -07005003#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005004 if (builtIn == spv::BuiltInSampleMask) {
5005 spv::Decoration decoration;
5006 // GL_NV_sample_mask_override_coverage extension
5007 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005008 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005009 else
5010 decoration = (spv::Decoration)spv::DecorationMax;
5011 addDecoration(id, decoration);
5012 if (decoration != spv::DecorationMax) {
5013 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5014 }
5015 }
chaoc771d89f2017-01-13 01:10:53 -08005016 else if (builtIn == spv::BuiltInLayer) {
5017 // SPV_NV_viewport_array2 extension
5018 if (symbol->getQualifier().layoutViewportRelative)
5019 {
5020 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5021 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5022 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5023 }
5024 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5025 {
5026 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5027 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5028 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5029 }
5030 }
5031
chaoc6e5acae2016-12-20 13:28:52 -08005032 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005033 addDecoration(id, spv::DecorationPassthroughNV);
5034 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005035 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5036 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005037#endif
5038
John Kessenich140f3df2015-06-26 16:58:36 -06005039 return id;
5040}
5041
John Kessenich55e7d112015-11-15 21:33:39 -07005042// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005043void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5044{
John Kessenich4016e382016-07-15 11:53:56 -06005045 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005046 builder.addDecoration(id, dec);
5047}
5048
John Kessenich55e7d112015-11-15 21:33:39 -07005049// If 'dec' is valid, add a one-operand decoration to an object
5050void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5051{
John Kessenich4016e382016-07-15 11:53:56 -06005052 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005053 builder.addDecoration(id, dec, value);
5054}
5055
5056// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005057void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5058{
John Kessenich4016e382016-07-15 11:53:56 -06005059 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005060 builder.addMemberDecoration(id, (unsigned)member, dec);
5061}
5062
John Kessenich92187592016-02-01 13:45:25 -07005063// If 'dec' is valid, add a one-operand decoration to a struct member
5064void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5065{
John Kessenich4016e382016-07-15 11:53:56 -06005066 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005067 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5068}
5069
John Kessenich55e7d112015-11-15 21:33:39 -07005070// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005071// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005072//
5073// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5074//
5075// Recursively walk the nodes. The nodes form a tree whose leaves are
5076// regular constants, which themselves are trees that createSpvConstant()
5077// recursively walks. So, this function walks the "top" of the tree:
5078// - emit specialization constant-building instructions for specConstant
5079// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005080spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005081{
John Kessenich7cc0e282016-03-20 00:46:02 -06005082 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005083
qining4f4bb812016-04-03 23:55:17 -04005084 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005085 if (! node.getQualifier().specConstant) {
5086 // hand off to the non-spec-constant path
5087 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5088 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005089 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005090 nextConst, false);
5091 }
5092
5093 // We now know we have a specialization constant to build
5094
John Kessenichd94c0032016-05-30 19:29:40 -06005095 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005096 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5097 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5098 std::vector<spv::Id> dimConstId;
5099 for (int dim = 0; dim < 3; ++dim) {
5100 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5101 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5102 if (specConst)
5103 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5104 }
5105 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5106 }
5107
5108 // An AST node labelled as specialization constant should be a symbol node.
5109 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5110 if (auto* sn = node.getAsSymbolNode()) {
5111 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005112 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5113 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5114 // will set the builder into spec constant op instruction generating mode.
5115 sub_tree->traverse(this);
5116 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005117 } else if (auto* const_union_array = &sn->getConstArray()){
5118 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005119 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5120 builder.addName(id, sn->getName().c_str());
5121 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005122 }
5123 }
qining4f4bb812016-04-03 23:55:17 -04005124
5125 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5126 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005127 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005128 exit(1);
5129 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005130}
5131
John Kessenich140f3df2015-06-26 16:58:36 -06005132// Use 'consts' as the flattened glslang source of scalar constants to recursively
5133// build the aggregate SPIR-V constant.
5134//
5135// If there are not enough elements present in 'consts', 0 will be substituted;
5136// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5137//
qining08408382016-03-21 09:51:37 -04005138spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005139{
5140 // vector of constants for SPIR-V
5141 std::vector<spv::Id> spvConsts;
5142
5143 // Type is used for struct and array constants
5144 spv::Id typeId = convertGlslangToSpvType(glslangType);
5145
5146 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005147 glslang::TType elementType(glslangType, 0);
5148 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005149 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005150 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005151 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005152 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005153 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005154 } else if (glslangType.getStruct()) {
5155 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5156 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005157 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005158 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005159 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5160 bool zero = nextConst >= consts.size();
5161 switch (glslangType.getBasicType()) {
5162 case glslang::EbtInt:
5163 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5164 break;
5165 case glslang::EbtUint:
5166 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5167 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005168 case glslang::EbtInt64:
5169 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5170 break;
5171 case glslang::EbtUint64:
5172 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5173 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005174 case glslang::EbtFloat:
5175 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5176 break;
5177 case glslang::EbtDouble:
5178 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5179 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005180#ifdef AMD_EXTENSIONS
5181 case glslang::EbtFloat16:
5182 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5183 break;
5184#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005185 case glslang::EbtBool:
5186 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5187 break;
5188 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005189 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005190 break;
5191 }
5192 ++nextConst;
5193 }
5194 } else {
5195 // we have a non-aggregate (scalar) constant
5196 bool zero = nextConst >= consts.size();
5197 spv::Id scalar = 0;
5198 switch (glslangType.getBasicType()) {
5199 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005200 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005201 break;
5202 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005203 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005204 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005205 case glslang::EbtInt64:
5206 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5207 break;
5208 case glslang::EbtUint64:
5209 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5210 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005211 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005212 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005213 break;
5214 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005215 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005216 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005217#ifdef AMD_EXTENSIONS
5218 case glslang::EbtFloat16:
5219 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5220 break;
5221#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005222 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005223 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005224 break;
5225 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005226 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005227 break;
5228 }
5229 ++nextConst;
5230 return scalar;
5231 }
5232
5233 return builder.makeCompositeConstant(typeId, spvConsts);
5234}
5235
John Kessenich7c1aa102015-10-15 13:29:11 -06005236// Return true if the node is a constant or symbol whose reading has no
5237// non-trivial observable cost or effect.
5238bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5239{
5240 // don't know what this is
5241 if (node == nullptr)
5242 return false;
5243
5244 // a constant is safe
5245 if (node->getAsConstantUnion() != nullptr)
5246 return true;
5247
5248 // not a symbol means non-trivial
5249 if (node->getAsSymbolNode() == nullptr)
5250 return false;
5251
5252 // a symbol, depends on what's being read
5253 switch (node->getType().getQualifier().storage) {
5254 case glslang::EvqTemporary:
5255 case glslang::EvqGlobal:
5256 case glslang::EvqIn:
5257 case glslang::EvqInOut:
5258 case glslang::EvqConst:
5259 case glslang::EvqConstReadOnly:
5260 case glslang::EvqUniform:
5261 return true;
5262 default:
5263 return false;
5264 }
qining25262b32016-05-06 17:25:16 -04005265}
John Kessenich7c1aa102015-10-15 13:29:11 -06005266
5267// A node is trivial if it is a single operation with no side effects.
5268// Error on the side of saying non-trivial.
5269// Return true if trivial.
5270bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5271{
5272 if (node == nullptr)
5273 return false;
5274
5275 // symbols and constants are trivial
5276 if (isTrivialLeaf(node))
5277 return true;
5278
5279 // otherwise, it needs to be a simple operation or one or two leaf nodes
5280
5281 // not a simple operation
5282 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5283 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5284 if (binaryNode == nullptr && unaryNode == nullptr)
5285 return false;
5286
5287 // not on leaf nodes
5288 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5289 return false;
5290
5291 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5292 return false;
5293 }
5294
5295 switch (node->getAsOperator()->getOp()) {
5296 case glslang::EOpLogicalNot:
5297 case glslang::EOpConvIntToBool:
5298 case glslang::EOpConvUintToBool:
5299 case glslang::EOpConvFloatToBool:
5300 case glslang::EOpConvDoubleToBool:
5301 case glslang::EOpEqual:
5302 case glslang::EOpNotEqual:
5303 case glslang::EOpLessThan:
5304 case glslang::EOpGreaterThan:
5305 case glslang::EOpLessThanEqual:
5306 case glslang::EOpGreaterThanEqual:
5307 case glslang::EOpIndexDirect:
5308 case glslang::EOpIndexDirectStruct:
5309 case glslang::EOpLogicalXor:
5310 case glslang::EOpAny:
5311 case glslang::EOpAll:
5312 return true;
5313 default:
5314 return false;
5315 }
5316}
5317
5318// Emit short-circuiting code, where 'right' is never evaluated unless
5319// the left side is true (for &&) or false (for ||).
5320spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5321{
5322 spv::Id boolTypeId = builder.makeBoolType();
5323
5324 // emit left operand
5325 builder.clearAccessChain();
5326 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005327 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005328
5329 // Operands to accumulate OpPhi operands
5330 std::vector<spv::Id> phiOperands;
5331 // accumulate left operand's phi information
5332 phiOperands.push_back(leftId);
5333 phiOperands.push_back(builder.getBuildPoint()->getId());
5334
5335 // Make the two kinds of operation symmetric with a "!"
5336 // || => emit "if (! left) result = right"
5337 // && => emit "if ( left) result = right"
5338 //
5339 // TODO: this runtime "not" for || could be avoided by adding functionality
5340 // to 'builder' to have an "else" without an "then"
5341 if (op == glslang::EOpLogicalOr)
5342 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5343
5344 // make an "if" based on the left value
5345 spv::Builder::If ifBuilder(leftId, builder);
5346
5347 // emit right operand as the "then" part of the "if"
5348 builder.clearAccessChain();
5349 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005350 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005351
5352 // accumulate left operand's phi information
5353 phiOperands.push_back(rightId);
5354 phiOperands.push_back(builder.getBuildPoint()->getId());
5355
5356 // finish the "if"
5357 ifBuilder.makeEndIf();
5358
5359 // phi together the two results
5360 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5361}
5362
Rex Xu9d93a232016-05-05 12:30:44 +08005363// Return type Id of the imported set of extended instructions corresponds to the name.
5364// Import this set if it has not been imported yet.
5365spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5366{
5367 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5368 return extBuiltinMap[name];
5369 else {
Rex Xu51596642016-09-21 18:56:12 +08005370 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005371 spv::Id extBuiltins = builder.import(name);
5372 extBuiltinMap[name] = extBuiltins;
5373 return extBuiltins;
5374 }
5375}
5376
John Kessenich140f3df2015-06-26 16:58:36 -06005377}; // end anonymous namespace
5378
5379namespace glslang {
5380
John Kessenich68d78fd2015-07-12 19:28:10 -06005381void GetSpirvVersion(std::string& version)
5382{
John Kessenich9e55f632015-07-15 10:03:39 -06005383 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005384 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005385 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005386 version = buf;
5387}
5388
John Kessenich140f3df2015-06-26 16:58:36 -06005389// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005390void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005391{
5392 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005393 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005394 if (out.fail())
5395 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005396 for (int i = 0; i < (int)spirv.size(); ++i) {
5397 unsigned int word = spirv[i];
5398 out.write((const char*)&word, 4);
5399 }
5400 out.close();
5401}
5402
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005403// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005404void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005405{
5406 std::ofstream out;
5407 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005408 if (out.fail())
5409 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005410 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005411 if (varName != nullptr) {
5412 out << "\t #pragma once" << std::endl;
5413 out << "const uint32_t " << varName << "[] = {" << std::endl;
5414 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005415 const int WORDS_PER_LINE = 8;
5416 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5417 out << "\t";
5418 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5419 const unsigned int word = spirv[i + j];
5420 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5421 if (i + j + 1 < (int)spirv.size()) {
5422 out << ",";
5423 }
5424 }
5425 out << std::endl;
5426 }
Flavio15017db2017-02-15 14:29:33 -08005427 if (varName != nullptr) {
5428 out << "};";
5429 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005430 out.close();
5431}
5432
John Kessenich140f3df2015-06-26 16:58:36 -06005433//
5434// Set up the glslang traversal
5435//
5436void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5437{
Lei Zhang17535f72016-05-04 15:55:59 -04005438 spv::SpvBuildLogger logger;
5439 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005440}
5441
Lei Zhang17535f72016-05-04 15:55:59 -04005442void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005443{
John Kessenich140f3df2015-06-26 16:58:36 -06005444 TIntermNode* root = intermediate.getTreeRoot();
5445
5446 if (root == 0)
5447 return;
5448
5449 glslang::GetThreadPoolAllocator().push();
5450
Lei Zhang17535f72016-05-04 15:55:59 -04005451 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005452 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005453 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005454 it.dumpSpv(spirv);
5455
5456 glslang::GetThreadPoolAllocator().pop();
5457}
5458
5459}; // end namespace glslang