blob: 10c2f9220c7587d53d19eeea9450fb4454612a0e [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
John Kessenich927608b2017-01-06 12:34:14 -070023// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
Lei Zhang17535f72016-05-04 15:55:59 -0400104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
steve-lunargf1709e72017-05-02 20:14:50 -0600125 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600126 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600127 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
128 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600129 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
130 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
131 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600132 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700133 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600134 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600135 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
136 glslang::TLayoutPacking, const glslang::TQualifier&);
137 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
138 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700139 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700140 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800141 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600142 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700143 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700144 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
145 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
146 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100147 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600148
John Kessenich6fccb3c2016-09-19 16:01:41 -0600149 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600150 void makeFunctions(const glslang::TIntermSequence&);
151 void makeGlobalInitializers(const glslang::TIntermSequence&);
152 void visitFunctions(const glslang::TIntermSequence&);
153 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800154 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600155 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
156 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600157 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
158
qining25262b32016-05-06 17:25:16 -0400159 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
160 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
161 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800162 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800163 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600164 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800165 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800166 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800167 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600168 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800169 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600170 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
171 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700172 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600173 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700174 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400175 spv::Id createSpvConstant(const glslang::TIntermTyped&);
176 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600177 bool isTrivialLeaf(const glslang::TIntermTyped* node);
178 bool isTrivial(const glslang::TIntermTyped* node);
179 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800180 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600181
182 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600183 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700184 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600185 int sequenceDepth;
186
Lei Zhang17535f72016-05-04 15:55:59 -0400187 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400188
John Kessenich140f3df2015-06-26 16:58:36 -0600189 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
190 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700191 bool inEntryPoint;
192 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700193 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700194 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600195 const glslang::TIntermediate* glslangIntermediate;
196 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800197 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600198
John Kessenich2f273362015-07-18 22:34:27 -0600199 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600200 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600201 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700202 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600203 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600204 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600205};
206
207//
208// Helper functions for translating glslang representations to SPIR-V enumerants.
209//
210
211// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700212spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600213{
John Kessenich66e2faf2016-03-12 18:34:36 -0700214 switch (source) {
215 case glslang::EShSourceGlsl:
216 switch (profile) {
217 case ENoProfile:
218 case ECoreProfile:
219 case ECompatibilityProfile:
220 return spv::SourceLanguageGLSL;
221 case EEsProfile:
222 return spv::SourceLanguageESSL;
223 default:
224 return spv::SourceLanguageUnknown;
225 }
226 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600227 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600228 default:
229 return spv::SourceLanguageUnknown;
230 }
231}
232
233// Translate glslang language (stage) to SPIR-V execution model.
234spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
235{
236 switch (stage) {
237 case EShLangVertex: return spv::ExecutionModelVertex;
238 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
239 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
240 case EShLangGeometry: return spv::ExecutionModelGeometry;
241 case EShLangFragment: return spv::ExecutionModelFragment;
242 case EShLangCompute: return spv::ExecutionModelGLCompute;
243 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700244 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600245 return spv::ExecutionModelFragment;
246 }
247}
248
John Kessenich140f3df2015-06-26 16:58:36 -0600249// Translate glslang sampler type to SPIR-V dimensionality.
250spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
251{
252 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700253 case glslang::Esd1D: return spv::Dim1D;
254 case glslang::Esd2D: return spv::Dim2D;
255 case glslang::Esd3D: return spv::Dim3D;
256 case glslang::EsdCube: return spv::DimCube;
257 case glslang::EsdRect: return spv::DimRect;
258 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700259 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600260 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700261 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600262 return spv::Dim2D;
263 }
264}
265
John Kessenichf6640762016-08-01 19:44:00 -0600266// Translate glslang precision to SPIR-V precision decorations.
267spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600268{
John Kessenichf6640762016-08-01 19:44:00 -0600269 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700270 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600271 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600272 default:
273 return spv::NoPrecision;
274 }
275}
276
John Kessenichf6640762016-08-01 19:44:00 -0600277// Translate glslang type to SPIR-V precision decorations.
278spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
279{
280 return TranslatePrecisionDecoration(type.getQualifier().precision);
281}
282
John Kessenich140f3df2015-06-26 16:58:36 -0600283// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600284spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600285{
286 if (type.getBasicType() == glslang::EbtBlock) {
287 switch (type.getQualifier().storage) {
288 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600289 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600290 case glslang::EvqVaryingIn: return spv::DecorationBlock;
291 case glslang::EvqVaryingOut: return spv::DecorationBlock;
292 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700293 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600294 break;
295 }
296 }
297
John Kessenich4016e382016-07-15 11:53:56 -0600298 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600299}
300
Rex Xu1da878f2016-02-21 20:59:01 +0800301// Translate glslang type to SPIR-V memory decorations.
302void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
303{
304 if (qualifier.coherent)
305 memory.push_back(spv::DecorationCoherent);
306 if (qualifier.volatil)
307 memory.push_back(spv::DecorationVolatile);
308 if (qualifier.restrict)
309 memory.push_back(spv::DecorationRestrict);
310 if (qualifier.readonly)
311 memory.push_back(spv::DecorationNonWritable);
312 if (qualifier.writeonly)
313 memory.push_back(spv::DecorationNonReadable);
314}
315
John Kessenich140f3df2015-06-26 16:58:36 -0600316// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700317spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600318{
319 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700320 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600321 case glslang::ElmRowMajor:
322 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700323 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600324 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700325 default:
326 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600327 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600328 }
329 } else {
330 switch (type.getBasicType()) {
331 default:
John Kessenich4016e382016-07-15 11:53:56 -0600332 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600333 break;
334 case glslang::EbtBlock:
335 switch (type.getQualifier().storage) {
336 case glslang::EvqUniform:
337 case glslang::EvqBuffer:
338 switch (type.getQualifier().layoutPacking) {
339 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600340 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
341 default:
John Kessenich4016e382016-07-15 11:53:56 -0600342 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600343 }
344 case glslang::EvqVaryingIn:
345 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700346 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600347 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600348 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700349 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600350 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600351 }
352 }
353 }
354}
355
356// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600357// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700358// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800359spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600360{
Rex Xubbceed72016-05-21 09:40:44 +0800361 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700362 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600363 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800364 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700365 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700366 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600367 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800368#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800369 else if (qualifier.explicitInterp) {
370 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800371 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800372 }
Rex Xu9d93a232016-05-05 12:30:44 +0800373#endif
Rex Xubbceed72016-05-21 09:40:44 +0800374 else
John Kessenich4016e382016-07-15 11:53:56 -0600375 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800376}
377
378// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600379// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800380// should be applied.
381spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
382{
383 if (qualifier.patch)
384 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700385 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600386 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700387 else if (qualifier.sample) {
388 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600389 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700390 } else
John Kessenich4016e382016-07-15 11:53:56 -0600391 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600392}
393
John Kessenich92187592016-02-01 13:45:25 -0700394// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700395spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600396{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700397 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600398 return spv::DecorationInvariant;
399 else
John Kessenich4016e382016-07-15 11:53:56 -0600400 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600401}
402
qining9220dbb2016-05-04 17:34:38 -0400403// If glslang type is noContraction, return SPIR-V NoContraction decoration.
404spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
405{
406 if (qualifier.noContraction)
407 return spv::DecorationNoContraction;
408 else
John Kessenich4016e382016-07-15 11:53:56 -0600409 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400410}
411
David Netoa901ffe2016-06-08 14:11:40 +0100412// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
413// associated capabilities when required. For some built-in variables, a capability
414// is generated only when using the variable in an executable instruction, but not when
415// just declaring a struct member variable with it. This is true for PointSize,
416// ClipDistance, and CullDistance.
417spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600418{
419 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700420 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600421 // Defer adding the capability until the built-in is actually used.
422 if (! memberDeclaration) {
423 switch (glslangIntermediate->getStage()) {
424 case EShLangGeometry:
425 builder.addCapability(spv::CapabilityGeometryPointSize);
426 break;
427 case EShLangTessControl:
428 case EShLangTessEvaluation:
429 builder.addCapability(spv::CapabilityTessellationPointSize);
430 break;
431 default:
432 break;
433 }
John Kessenich92187592016-02-01 13:45:25 -0700434 }
435 return spv::BuiltInPointSize;
436
John Kessenichebb50532016-05-16 19:22:05 -0600437 // These *Distance capabilities logically belong here, but if the member is declared and
438 // then never used, consumers of SPIR-V prefer the capability not be declared.
439 // They are now generated when used, rather than here when declared.
440 // Potentially, the specification should be more clear what the minimum
441 // use needed is to trigger the capability.
442 //
John Kessenich92187592016-02-01 13:45:25 -0700443 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100444 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800445 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700446 return spv::BuiltInClipDistance;
447
448 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100449 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800450 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700451 return spv::BuiltInCullDistance;
452
453 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800454 if (!memberDeclaration) {
455 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800456#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800457 if (glslangIntermediate->getStage() == EShLangVertex ||
458 glslangIntermediate->getStage() == EShLangTessControl ||
459 glslangIntermediate->getStage() == EShLangTessEvaluation) {
460
461 builder.addExtension(spv::E_SPV_NV_viewport_array2);
462 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
463 }
chaoc771d89f2017-01-13 01:10:53 -0800464#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800465 }
John Kessenich92187592016-02-01 13:45:25 -0700466 return spv::BuiltInViewportIndex;
467
John Kessenich5e801132016-02-15 11:09:46 -0700468 case glslang::EbvSampleId:
469 builder.addCapability(spv::CapabilitySampleRateShading);
470 return spv::BuiltInSampleId;
471
472 case glslang::EbvSamplePosition:
473 builder.addCapability(spv::CapabilitySampleRateShading);
474 return spv::BuiltInSamplePosition;
475
476 case glslang::EbvSampleMask:
477 builder.addCapability(spv::CapabilitySampleRateShading);
478 return spv::BuiltInSampleMask;
479
John Kessenich78a45572016-07-08 14:05:15 -0600480 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800481 if (!memberDeclaration) {
482 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800483#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800484 if (glslangIntermediate->getStage() == EShLangVertex ||
485 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800486 glslangIntermediate->getStage() == EShLangTessEvaluation) {
487
chaoc771d89f2017-01-13 01:10:53 -0800488 builder.addExtension(spv::E_SPV_NV_viewport_array2);
489 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
490 }
chaoc771d89f2017-01-13 01:10:53 -0800491#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800492 }
493
John Kessenich78a45572016-07-08 14:05:15 -0600494 return spv::BuiltInLayer;
495
John Kessenich140f3df2015-06-26 16:58:36 -0600496 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600497 case glslang::EbvVertexId: return spv::BuiltInVertexId;
498 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700499 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
500 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800501
John Kessenichda581a22015-10-14 14:10:30 -0600502 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800503 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
504 builder.addCapability(spv::CapabilityDrawParameters);
505 return spv::BuiltInBaseVertex;
506
John Kessenichda581a22015-10-14 14:10:30 -0600507 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800508 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
509 builder.addCapability(spv::CapabilityDrawParameters);
510 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200511
John Kessenichda581a22015-10-14 14:10:30 -0600512 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800513 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
514 builder.addCapability(spv::CapabilityDrawParameters);
515 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200516
517 case glslang::EbvPrimitiveId:
518 if (glslangIntermediate->getStage() == EShLangFragment)
519 builder.addCapability(spv::CapabilityGeometry);
520 return spv::BuiltInPrimitiveId;
521
John Kessenich140f3df2015-06-26 16:58:36 -0600522 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600523 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
524 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
525 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
526 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
527 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
528 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
529 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600530 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
531 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
532 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
533 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
534 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
535 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
536 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
537 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800538
Rex Xu574ab042016-04-14 16:53:07 +0800539 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800540 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800541 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
542 return spv::BuiltInSubgroupSize;
543
Rex Xu574ab042016-04-14 16:53:07 +0800544 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800545 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800546 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
547 return spv::BuiltInSubgroupLocalInvocationId;
548
Rex Xu574ab042016-04-14 16:53:07 +0800549 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800550 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
551 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
552 return spv::BuiltInSubgroupEqMaskKHR;
553
Rex Xu574ab042016-04-14 16:53:07 +0800554 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800555 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
556 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
557 return spv::BuiltInSubgroupGeMaskKHR;
558
Rex Xu574ab042016-04-14 16:53:07 +0800559 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800560 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
561 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
562 return spv::BuiltInSubgroupGtMaskKHR;
563
Rex Xu574ab042016-04-14 16:53:07 +0800564 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800565 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
566 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
567 return spv::BuiltInSubgroupLeMaskKHR;
568
Rex Xu574ab042016-04-14 16:53:07 +0800569 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800570 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
571 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
572 return spv::BuiltInSubgroupLtMaskKHR;
573
Rex Xu9d93a232016-05-05 12:30:44 +0800574#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800575 case glslang::EbvBaryCoordNoPersp:
576 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
577 return spv::BuiltInBaryCoordNoPerspAMD;
578
579 case glslang::EbvBaryCoordNoPerspCentroid:
580 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
581 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
582
583 case glslang::EbvBaryCoordNoPerspSample:
584 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
585 return spv::BuiltInBaryCoordNoPerspSampleAMD;
586
587 case glslang::EbvBaryCoordSmooth:
588 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
589 return spv::BuiltInBaryCoordSmoothAMD;
590
591 case glslang::EbvBaryCoordSmoothCentroid:
592 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
593 return spv::BuiltInBaryCoordSmoothCentroidAMD;
594
595 case glslang::EbvBaryCoordSmoothSample:
596 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
597 return spv::BuiltInBaryCoordSmoothSampleAMD;
598
599 case glslang::EbvBaryCoordPullModel:
600 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
601 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800602#endif
chaoc771d89f2017-01-13 01:10:53 -0800603
John Kessenich6c8aaac2017-02-27 01:20:51 -0700604 case glslang::EbvDeviceIndex:
605 builder.addExtension(spv::E_SPV_KHR_device_group);
606 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700607 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700608
609 case glslang::EbvViewIndex:
610 builder.addExtension(spv::E_SPV_KHR_multiview);
611 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700612 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700613
chaoc771d89f2017-01-13 01:10:53 -0800614#ifdef NV_EXTENSIONS
615 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800616 if (!memberDeclaration) {
617 builder.addExtension(spv::E_SPV_NV_viewport_array2);
618 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
619 }
chaoc771d89f2017-01-13 01:10:53 -0800620 return spv::BuiltInViewportMaskNV;
621 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800622 if (!memberDeclaration) {
623 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
624 builder.addCapability(spv::CapabilityShaderStereoViewNV);
625 }
chaoc771d89f2017-01-13 01:10:53 -0800626 return spv::BuiltInSecondaryPositionNV;
627 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800628 if (!memberDeclaration) {
629 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
630 builder.addCapability(spv::CapabilityShaderStereoViewNV);
631 }
chaoc771d89f2017-01-13 01:10:53 -0800632 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800633 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800634 if (!memberDeclaration) {
635 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
636 builder.addCapability(spv::CapabilityPerViewAttributesNV);
637 }
chaocdf3956c2017-02-14 14:52:34 -0800638 return spv::BuiltInPositionPerViewNV;
639 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800640 if (!memberDeclaration) {
641 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
642 builder.addCapability(spv::CapabilityPerViewAttributesNV);
643 }
chaocdf3956c2017-02-14 14:52:34 -0800644 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800645#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800646 default:
647 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600648 }
649}
650
Rex Xufc618912015-09-09 16:42:49 +0800651// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700652spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800653{
654 assert(type.getBasicType() == glslang::EbtSampler);
655
John Kessenich5d0fa972016-02-15 11:57:00 -0700656 // Check for capabilities
657 switch (type.getQualifier().layoutFormat) {
658 case glslang::ElfRg32f:
659 case glslang::ElfRg16f:
660 case glslang::ElfR11fG11fB10f:
661 case glslang::ElfR16f:
662 case glslang::ElfRgba16:
663 case glslang::ElfRgb10A2:
664 case glslang::ElfRg16:
665 case glslang::ElfRg8:
666 case glslang::ElfR16:
667 case glslang::ElfR8:
668 case glslang::ElfRgba16Snorm:
669 case glslang::ElfRg16Snorm:
670 case glslang::ElfRg8Snorm:
671 case glslang::ElfR16Snorm:
672 case glslang::ElfR8Snorm:
673
674 case glslang::ElfRg32i:
675 case glslang::ElfRg16i:
676 case glslang::ElfRg8i:
677 case glslang::ElfR16i:
678 case glslang::ElfR8i:
679
680 case glslang::ElfRgb10a2ui:
681 case glslang::ElfRg32ui:
682 case glslang::ElfRg16ui:
683 case glslang::ElfRg8ui:
684 case glslang::ElfR16ui:
685 case glslang::ElfR8ui:
686 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
687 break;
688
689 default:
690 break;
691 }
692
693 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800694 switch (type.getQualifier().layoutFormat) {
695 case glslang::ElfNone: return spv::ImageFormatUnknown;
696 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
697 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
698 case glslang::ElfR32f: return spv::ImageFormatR32f;
699 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
700 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
701 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
702 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
703 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
704 case glslang::ElfR16f: return spv::ImageFormatR16f;
705 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
706 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
707 case glslang::ElfRg16: return spv::ImageFormatRg16;
708 case glslang::ElfRg8: return spv::ImageFormatRg8;
709 case glslang::ElfR16: return spv::ImageFormatR16;
710 case glslang::ElfR8: return spv::ImageFormatR8;
711 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
712 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
713 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
714 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
715 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
716 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
717 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
718 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
719 case glslang::ElfR32i: return spv::ImageFormatR32i;
720 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
721 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
722 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
723 case glslang::ElfR16i: return spv::ImageFormatR16i;
724 case glslang::ElfR8i: return spv::ImageFormatR8i;
725 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
726 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
727 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
728 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
729 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
730 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
731 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
732 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
733 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
734 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600735 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800736 }
737}
738
steve-lunargf1709e72017-05-02 20:14:50 -0600739spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
740{
741 switch (loopControl) {
742 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
743 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
744 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
745 // TODO: DependencyInfinite
746 // TODO: DependencyLength
747 default: return spv::LoopControlMaskNone;
748 }
749}
750
John Kessenicha5c5fb62017-05-05 05:09:58 -0600751// Translate glslang type to SPIR-V storage class.
752spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
753{
754 if (type.getQualifier().isPipeInput())
755 return spv::StorageClassInput;
756 else if (type.getQualifier().isPipeOutput())
757 return spv::StorageClassOutput;
758 else if (type.getBasicType() == glslang::EbtAtomicUint)
759 return spv::StorageClassAtomicCounter;
760 else if (type.containsOpaque())
761 return spv::StorageClassUniformConstant;
762 else if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
763 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
764 return spv::StorageClassStorageBuffer;
765 } else if (type.getQualifier().isUniformOrBuffer()) {
766 if (type.getQualifier().layoutPushConstant)
767 return spv::StorageClassPushConstant;
768 if (type.getBasicType() == glslang::EbtBlock)
769 return spv::StorageClassUniform;
770 else
771 return spv::StorageClassUniformConstant;
772 } else {
773 switch (type.getQualifier().storage) {
774 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
775 case glslang::EvqGlobal: return spv::StorageClassPrivate;
776 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
777 case glslang::EvqTemporary: return spv::StorageClassFunction;
778 default:
779 assert(0);
780 return spv::StorageClassFunction;
781 }
782 }
783}
784
qining25262b32016-05-06 17:25:16 -0400785// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700786// descriptor set.
787bool IsDescriptorResource(const glslang::TType& type)
788{
John Kessenichf7497e22016-03-08 21:36:22 -0700789 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700790 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700791 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700792
793 // non block...
794 // basically samplerXXX/subpass/sampler/texture are all included
795 // if they are the global-scope-class, not the function parameter
796 // (or local, if they ever exist) class.
797 if (type.getBasicType() == glslang::EbtSampler)
798 return type.getQualifier().isUniformOrBuffer();
799
800 // None of the above.
801 return false;
802}
803
John Kesseniche0b6cad2015-12-24 10:30:13 -0700804void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
805{
806 if (child.layoutMatrix == glslang::ElmNone)
807 child.layoutMatrix = parent.layoutMatrix;
808
809 if (parent.invariant)
810 child.invariant = true;
811 if (parent.nopersp)
812 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800813#ifdef AMD_EXTENSIONS
814 if (parent.explicitInterp)
815 child.explicitInterp = true;
816#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700817 if (parent.flat)
818 child.flat = true;
819 if (parent.centroid)
820 child.centroid = true;
821 if (parent.patch)
822 child.patch = true;
823 if (parent.sample)
824 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800825 if (parent.coherent)
826 child.coherent = true;
827 if (parent.volatil)
828 child.volatil = true;
829 if (parent.restrict)
830 child.restrict = true;
831 if (parent.readonly)
832 child.readonly = true;
833 if (parent.writeonly)
834 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700835}
836
John Kessenichf2b7f332016-09-01 17:05:23 -0600837bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700838{
John Kessenich7b9fa252016-01-21 18:56:57 -0700839 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600840 // - struct members might inherit from a struct declaration
841 // (note that non-block structs don't explicitly inherit,
842 // only implicitly, meaning no decoration involved)
843 // - affect decorations on the struct members
844 // (note smooth does not, and expecting something like volatile
845 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700846 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600847 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700848}
849
John Kessenich140f3df2015-06-26 16:58:36 -0600850//
851// Implement the TGlslangToSpvTraverser class.
852//
853
Lei Zhang17535f72016-05-04 15:55:59 -0400854TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600855 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
856 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400857 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700858 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600859 glslangIntermediate(glslangIntermediate)
860{
861 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
862
863 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700864 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600865 stdBuiltins = builder.import("GLSL.std.450");
866 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600867 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
868 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600869
870 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600871 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
872 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600873 builder.addSourceExtension(it->c_str());
874
875 // Add the top-level modes for this shader.
876
John Kessenich92187592016-02-01 13:45:25 -0700877 if (glslangIntermediate->getXfbMode()) {
878 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600879 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700880 }
John Kessenich140f3df2015-06-26 16:58:36 -0600881
882 unsigned int mode;
883 switch (glslangIntermediate->getStage()) {
884 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600885 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600886 break;
887
steve-lunarge7412492017-03-23 11:56:07 -0600888 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600889 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600890 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600891
steve-lunarge7412492017-03-23 11:56:07 -0600892 glslang::TLayoutGeometry primitive;
893
894 if (glslangIntermediate->getStage() == EShLangTessControl) {
895 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
896 primitive = glslangIntermediate->getOutputPrimitive();
897 } else {
898 primitive = glslangIntermediate->getInputPrimitive();
899 }
900
901 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700902 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
903 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
904 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600905 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600906 }
John Kessenich4016e382016-07-15 11:53:56 -0600907 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600908 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
909
John Kesseniche6903322015-10-13 16:29:02 -0600910 switch (glslangIntermediate->getVertexSpacing()) {
911 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
912 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
913 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600914 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600915 }
John Kessenich4016e382016-07-15 11:53:56 -0600916 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600917 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
918
919 switch (glslangIntermediate->getVertexOrder()) {
920 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
921 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600922 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600923 }
John Kessenich4016e382016-07-15 11:53:56 -0600924 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600925 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
926
927 if (glslangIntermediate->getPointMode())
928 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600929 break;
930
931 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600932 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600933 switch (glslangIntermediate->getInputPrimitive()) {
934 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
935 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
936 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700937 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600938 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600939 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600940 }
John Kessenich4016e382016-07-15 11:53:56 -0600941 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600942 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600943
John Kessenich140f3df2015-06-26 16:58:36 -0600944 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
945
946 switch (glslangIntermediate->getOutputPrimitive()) {
947 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
948 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
949 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600950 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600951 }
John Kessenich4016e382016-07-15 11:53:56 -0600952 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600953 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
954 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
955 break;
956
957 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600958 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600959 if (glslangIntermediate->getPixelCenterInteger())
960 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600961
John Kessenich140f3df2015-06-26 16:58:36 -0600962 if (glslangIntermediate->getOriginUpperLeft())
963 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600964 else
965 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600966
967 if (glslangIntermediate->getEarlyFragmentTests())
968 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
969
970 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600971 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
972 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600973 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600974 }
John Kessenich4016e382016-07-15 11:53:56 -0600975 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600976 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
977
978 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
979 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600980 break;
981
982 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600983 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600984 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
985 glslangIntermediate->getLocalSize(1),
986 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600987 break;
988
989 default:
990 break;
991 }
John Kessenich140f3df2015-06-26 16:58:36 -0600992}
993
John Kessenichfca82622016-11-26 13:23:20 -0700994// Finish creating SPV, after the traversal is complete.
995void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700996{
John Kessenich517fe7a2016-11-26 13:31:47 -0700997 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700998 builder.setBuildPoint(shaderEntry->getLastBlock());
999 builder.leaveFunction();
1000 }
1001
John Kessenich7ba63412015-12-20 17:37:07 -07001002 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001003 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1004 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001005
qiningda397332016-03-09 19:54:03 -05001006 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001007}
1008
John Kessenichfca82622016-11-26 13:23:20 -07001009// Write the SPV into 'out'.
1010void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001011{
John Kessenichfca82622016-11-26 13:23:20 -07001012 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001013}
1014
1015//
1016// Implement the traversal functions.
1017//
1018// Return true from interior nodes to have the external traversal
1019// continue on to children. Return false if children were
1020// already processed.
1021//
1022
1023//
qining25262b32016-05-06 17:25:16 -04001024// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001025// - uniform/input reads
1026// - output writes
1027// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1028// - something simple that degenerates into the last bullet
1029//
1030void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1031{
qining75d1d802016-04-06 14:42:01 -04001032 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1033 if (symbol->getType().getQualifier().isSpecConstant())
1034 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1035
John Kessenich140f3df2015-06-26 16:58:36 -06001036 // getSymbolId() will set up all the IO decorations on the first call.
1037 // Formal function parameters were mapped during makeFunctions().
1038 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001039
1040 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1041 if (builder.isPointer(id)) {
1042 spv::StorageClass sc = builder.getStorageClass(id);
1043 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1044 iOSet.insert(id);
1045 }
1046
1047 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001048 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001049 // Prepare to generate code for the access
1050
1051 // L-value chains will be computed left to right. We're on the symbol now,
1052 // which is the left-most part of the access chain, so now is "clear" time,
1053 // followed by setting the base.
1054 builder.clearAccessChain();
1055
1056 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001057 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001058 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001059 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001060 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001061 // These are also pure R-values.
1062 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001063 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001064 builder.setAccessChainRValue(id);
1065 else
1066 builder.setAccessChainLValue(id);
1067 }
1068}
1069
1070bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1071{
qining40887662016-04-03 22:20:42 -04001072 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1073 if (node->getType().getQualifier().isSpecConstant())
1074 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1075
John Kessenich140f3df2015-06-26 16:58:36 -06001076 // First, handle special cases
1077 switch (node->getOp()) {
1078 case glslang::EOpAssign:
1079 case glslang::EOpAddAssign:
1080 case glslang::EOpSubAssign:
1081 case glslang::EOpMulAssign:
1082 case glslang::EOpVectorTimesMatrixAssign:
1083 case glslang::EOpVectorTimesScalarAssign:
1084 case glslang::EOpMatrixTimesScalarAssign:
1085 case glslang::EOpMatrixTimesMatrixAssign:
1086 case glslang::EOpDivAssign:
1087 case glslang::EOpModAssign:
1088 case glslang::EOpAndAssign:
1089 case glslang::EOpInclusiveOrAssign:
1090 case glslang::EOpExclusiveOrAssign:
1091 case glslang::EOpLeftShiftAssign:
1092 case glslang::EOpRightShiftAssign:
1093 // A bin-op assign "a += b" means the same thing as "a = a + b"
1094 // where a is evaluated before b. For a simple assignment, GLSL
1095 // says to evaluate the left before the right. So, always, left
1096 // node then right node.
1097 {
1098 // get the left l-value, save it away
1099 builder.clearAccessChain();
1100 node->getLeft()->traverse(this);
1101 spv::Builder::AccessChain lValue = builder.getAccessChain();
1102
1103 // evaluate the right
1104 builder.clearAccessChain();
1105 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001106 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001107
1108 if (node->getOp() != glslang::EOpAssign) {
1109 // the left is also an r-value
1110 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001111 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001112
1113 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001114 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001115 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001116 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1117 node->getType().getBasicType());
1118
1119 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001120 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001121 }
1122
1123 // store the result
1124 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001125 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001126
1127 // assignments are expressions having an rValue after they are evaluated...
1128 builder.clearAccessChain();
1129 builder.setAccessChainRValue(rValue);
1130 }
1131 return false;
1132 case glslang::EOpIndexDirect:
1133 case glslang::EOpIndexDirectStruct:
1134 {
1135 // Get the left part of the access chain.
1136 node->getLeft()->traverse(this);
1137
1138 // Add the next element in the chain
1139
David Netoa901ffe2016-06-08 14:11:40 +01001140 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001141 if (! node->getLeft()->getType().isArray() &&
1142 node->getLeft()->getType().isVector() &&
1143 node->getOp() == glslang::EOpIndexDirect) {
1144 // This is essentially a hard-coded vector swizzle of size 1,
1145 // so short circuit the access-chain stuff with a swizzle.
1146 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001147 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001148 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001149 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001150 int spvIndex = glslangIndex;
1151 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1152 node->getOp() == glslang::EOpIndexDirectStruct)
1153 {
1154 // This may be, e.g., an anonymous block-member selection, which generally need
1155 // index remapping due to hidden members in anonymous blocks.
1156 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1157 assert(remapper.size() > 0);
1158 spvIndex = remapper[glslangIndex];
1159 }
John Kessenichebb50532016-05-16 19:22:05 -06001160
David Netoa901ffe2016-06-08 14:11:40 +01001161 // normal case for indexing array or structure or block
1162 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1163
1164 // Add capabilities here for accessing PointSize and clip/cull distance.
1165 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001166 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001167 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001168 }
1169 }
1170 return false;
1171 case glslang::EOpIndexIndirect:
1172 {
1173 // Structure or array or vector indirection.
1174 // Will use native SPIR-V access-chain for struct and array indirection;
1175 // matrices are arrays of vectors, so will also work for a matrix.
1176 // Will use the access chain's 'component' for variable index into a vector.
1177
1178 // This adapter is building access chains left to right.
1179 // Set up the access chain to the left.
1180 node->getLeft()->traverse(this);
1181
1182 // save it so that computing the right side doesn't trash it
1183 spv::Builder::AccessChain partial = builder.getAccessChain();
1184
1185 // compute the next index in the chain
1186 builder.clearAccessChain();
1187 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001188 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001189
1190 // restore the saved access chain
1191 builder.setAccessChain(partial);
1192
1193 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001194 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001195 else
John Kessenichfa668da2015-09-13 14:46:30 -06001196 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001197 }
1198 return false;
1199 case glslang::EOpVectorSwizzle:
1200 {
1201 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001202 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001203 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001204 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001205 }
1206 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001207 case glslang::EOpMatrixSwizzle:
1208 logger->missingFunctionality("matrix swizzle");
1209 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001210 case glslang::EOpLogicalOr:
1211 case glslang::EOpLogicalAnd:
1212 {
1213
1214 // These may require short circuiting, but can sometimes be done as straight
1215 // binary operations. The right operand must be short circuited if it has
1216 // side effects, and should probably be if it is complex.
1217 if (isTrivial(node->getRight()->getAsTyped()))
1218 break; // handle below as a normal binary operation
1219 // otherwise, we need to do dynamic short circuiting on the right operand
1220 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1221 builder.clearAccessChain();
1222 builder.setAccessChainRValue(result);
1223 }
1224 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001225 default:
1226 break;
1227 }
1228
1229 // Assume generic binary op...
1230
John Kessenich32cfd492016-02-02 12:37:46 -07001231 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001232 builder.clearAccessChain();
1233 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001234 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001235
John Kessenich32cfd492016-02-02 12:37:46 -07001236 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001237 builder.clearAccessChain();
1238 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001239 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001240
John Kessenich32cfd492016-02-02 12:37:46 -07001241 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001242 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001243 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001244 convertGlslangToSpvType(node->getType()), left, right,
1245 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001246
John Kessenich50e57562015-12-21 21:21:11 -07001247 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001248 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001249 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001250 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001251 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001252 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001253 return false;
1254 }
John Kessenich140f3df2015-06-26 16:58:36 -06001255}
1256
1257bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1258{
qining40887662016-04-03 22:20:42 -04001259 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1260 if (node->getType().getQualifier().isSpecConstant())
1261 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1262
John Kessenichfc51d282015-08-19 13:34:18 -06001263 spv::Id result = spv::NoResult;
1264
1265 // try texturing first
1266 result = createImageTextureFunctionCall(node);
1267 if (result != spv::NoResult) {
1268 builder.clearAccessChain();
1269 builder.setAccessChainRValue(result);
1270
1271 return false; // done with this node
1272 }
1273
1274 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001275
1276 if (node->getOp() == glslang::EOpArrayLength) {
1277 // Quite special; won't want to evaluate the operand.
1278
1279 // Normal .length() would have been constant folded by the front-end.
1280 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001281 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001282 assert(node->getOperand()->getType().isRuntimeSizedArray());
1283 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1284 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001285 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1286 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001287
1288 builder.clearAccessChain();
1289 builder.setAccessChainRValue(length);
1290
1291 return false;
1292 }
1293
John Kessenichfc51d282015-08-19 13:34:18 -06001294 // Start by evaluating the operand
1295
John Kessenich8c8505c2016-07-26 12:50:38 -06001296 // Does it need a swizzle inversion? If so, evaluation is inverted;
1297 // operate first on the swizzle base, then apply the swizzle.
1298 spv::Id invertedType = spv::NoType;
1299 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1300 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1301 invertedType = getInvertedSwizzleType(*node->getOperand());
1302
John Kessenich140f3df2015-06-26 16:58:36 -06001303 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001304 if (invertedType != spv::NoType)
1305 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1306 else
1307 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001308
Rex Xufc618912015-09-09 16:42:49 +08001309 spv::Id operand = spv::NoResult;
1310
1311 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1312 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001313 node->getOp() == glslang::EOpAtomicCounter ||
1314 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001315 operand = builder.accessChainGetLValue(); // Special case l-value operands
1316 else
John Kessenich32cfd492016-02-02 12:37:46 -07001317 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001318
John Kessenichf6640762016-08-01 19:44:00 -06001319 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001320 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001321
1322 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001323 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001324 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001325
1326 // if not, then possibly an operation
1327 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001328 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001329
1330 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001331 if (invertedType)
1332 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1333
John Kessenich140f3df2015-06-26 16:58:36 -06001334 builder.clearAccessChain();
1335 builder.setAccessChainRValue(result);
1336
1337 return false; // done with this node
1338 }
1339
1340 // it must be a special case, check...
1341 switch (node->getOp()) {
1342 case glslang::EOpPostIncrement:
1343 case glslang::EOpPostDecrement:
1344 case glslang::EOpPreIncrement:
1345 case glslang::EOpPreDecrement:
1346 {
1347 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001348 spv::Id one = 0;
1349 if (node->getBasicType() == glslang::EbtFloat)
1350 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001351 else if (node->getBasicType() == glslang::EbtDouble)
1352 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001353#ifdef AMD_EXTENSIONS
1354 else if (node->getBasicType() == glslang::EbtFloat16)
1355 one = builder.makeFloat16Constant(1.0F);
1356#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001357 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1358 one = builder.makeInt64Constant(1);
1359 else
1360 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001361 glslang::TOperator op;
1362 if (node->getOp() == glslang::EOpPreIncrement ||
1363 node->getOp() == glslang::EOpPostIncrement)
1364 op = glslang::EOpAdd;
1365 else
1366 op = glslang::EOpSub;
1367
John Kessenichf6640762016-08-01 19:44:00 -06001368 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001369 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001370 convertGlslangToSpvType(node->getType()), operand, one,
1371 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001372 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001373
1374 // The result of operation is always stored, but conditionally the
1375 // consumed result. The consumed result is always an r-value.
1376 builder.accessChainStore(result);
1377 builder.clearAccessChain();
1378 if (node->getOp() == glslang::EOpPreIncrement ||
1379 node->getOp() == glslang::EOpPreDecrement)
1380 builder.setAccessChainRValue(result);
1381 else
1382 builder.setAccessChainRValue(operand);
1383 }
1384
1385 return false;
1386
1387 case glslang::EOpEmitStreamVertex:
1388 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1389 return false;
1390 case glslang::EOpEndStreamPrimitive:
1391 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1392 return false;
1393
1394 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001395 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001396 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001397 }
John Kessenich140f3df2015-06-26 16:58:36 -06001398}
1399
1400bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1401{
qining27e04a02016-04-14 16:40:20 -04001402 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1403 if (node->getType().getQualifier().isSpecConstant())
1404 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1405
John Kessenichfc51d282015-08-19 13:34:18 -06001406 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001407 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1408 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001409
1410 // try texturing
1411 result = createImageTextureFunctionCall(node);
1412 if (result != spv::NoResult) {
1413 builder.clearAccessChain();
1414 builder.setAccessChainRValue(result);
1415
1416 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001417 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001418 // "imageStore" is a special case, which has no result
1419 return false;
1420 }
John Kessenichfc51d282015-08-19 13:34:18 -06001421
John Kessenich140f3df2015-06-26 16:58:36 -06001422 glslang::TOperator binOp = glslang::EOpNull;
1423 bool reduceComparison = true;
1424 bool isMatrix = false;
1425 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001426 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001427
1428 assert(node->getOp());
1429
John Kessenichf6640762016-08-01 19:44:00 -06001430 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001431
1432 switch (node->getOp()) {
1433 case glslang::EOpSequence:
1434 {
1435 if (preVisit)
1436 ++sequenceDepth;
1437 else
1438 --sequenceDepth;
1439
1440 if (sequenceDepth == 1) {
1441 // If this is the parent node of all the functions, we want to see them
1442 // early, so all call points have actual SPIR-V functions to reference.
1443 // In all cases, still let the traverser visit the children for us.
1444 makeFunctions(node->getAsAggregate()->getSequence());
1445
John Kessenich6fccb3c2016-09-19 16:01:41 -06001446 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001447 // anything else gets there, so visit out of order, doing them all now.
1448 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1449
John Kessenich6a60c2f2016-12-08 21:01:59 -07001450 // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
John Kessenich140f3df2015-06-26 16:58:36 -06001451 // so do them manually.
1452 visitFunctions(node->getAsAggregate()->getSequence());
1453
1454 return false;
1455 }
1456
1457 return true;
1458 }
1459 case glslang::EOpLinkerObjects:
1460 {
1461 if (visit == glslang::EvPreVisit)
1462 linkageOnly = true;
1463 else
1464 linkageOnly = false;
1465
1466 return true;
1467 }
1468 case glslang::EOpComma:
1469 {
1470 // processing from left to right naturally leaves the right-most
1471 // lying around in the access chain
1472 glslang::TIntermSequence& glslangOperands = node->getSequence();
1473 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1474 glslangOperands[i]->traverse(this);
1475
1476 return false;
1477 }
1478 case glslang::EOpFunction:
1479 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001480 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001481 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001482 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001483 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001484 } else {
1485 handleFunctionEntry(node);
1486 }
1487 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001488 if (inEntryPoint)
1489 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001490 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001491 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001492 }
1493
1494 return true;
1495 case glslang::EOpParameters:
1496 // Parameters will have been consumed by EOpFunction processing, but not
1497 // the body, so we still visited the function node's children, making this
1498 // child redundant.
1499 return false;
1500 case glslang::EOpFunctionCall:
1501 {
1502 if (node->isUserDefined())
1503 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001504 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07001505 if (result) {
1506 builder.clearAccessChain();
1507 builder.setAccessChainRValue(result);
1508 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001509 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001510
1511 return false;
1512 }
1513 case glslang::EOpConstructMat2x2:
1514 case glslang::EOpConstructMat2x3:
1515 case glslang::EOpConstructMat2x4:
1516 case glslang::EOpConstructMat3x2:
1517 case glslang::EOpConstructMat3x3:
1518 case glslang::EOpConstructMat3x4:
1519 case glslang::EOpConstructMat4x2:
1520 case glslang::EOpConstructMat4x3:
1521 case glslang::EOpConstructMat4x4:
1522 case glslang::EOpConstructDMat2x2:
1523 case glslang::EOpConstructDMat2x3:
1524 case glslang::EOpConstructDMat2x4:
1525 case glslang::EOpConstructDMat3x2:
1526 case glslang::EOpConstructDMat3x3:
1527 case glslang::EOpConstructDMat3x4:
1528 case glslang::EOpConstructDMat4x2:
1529 case glslang::EOpConstructDMat4x3:
1530 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001531#ifdef AMD_EXTENSIONS
1532 case glslang::EOpConstructF16Mat2x2:
1533 case glslang::EOpConstructF16Mat2x3:
1534 case glslang::EOpConstructF16Mat2x4:
1535 case glslang::EOpConstructF16Mat3x2:
1536 case glslang::EOpConstructF16Mat3x3:
1537 case glslang::EOpConstructF16Mat3x4:
1538 case glslang::EOpConstructF16Mat4x2:
1539 case glslang::EOpConstructF16Mat4x3:
1540 case glslang::EOpConstructF16Mat4x4:
1541#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001542 isMatrix = true;
1543 // fall through
1544 case glslang::EOpConstructFloat:
1545 case glslang::EOpConstructVec2:
1546 case glslang::EOpConstructVec3:
1547 case glslang::EOpConstructVec4:
1548 case glslang::EOpConstructDouble:
1549 case glslang::EOpConstructDVec2:
1550 case glslang::EOpConstructDVec3:
1551 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001552#ifdef AMD_EXTENSIONS
1553 case glslang::EOpConstructFloat16:
1554 case glslang::EOpConstructF16Vec2:
1555 case glslang::EOpConstructF16Vec3:
1556 case glslang::EOpConstructF16Vec4:
1557#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001558 case glslang::EOpConstructBool:
1559 case glslang::EOpConstructBVec2:
1560 case glslang::EOpConstructBVec3:
1561 case glslang::EOpConstructBVec4:
1562 case glslang::EOpConstructInt:
1563 case glslang::EOpConstructIVec2:
1564 case glslang::EOpConstructIVec3:
1565 case glslang::EOpConstructIVec4:
1566 case glslang::EOpConstructUint:
1567 case glslang::EOpConstructUVec2:
1568 case glslang::EOpConstructUVec3:
1569 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001570 case glslang::EOpConstructInt64:
1571 case glslang::EOpConstructI64Vec2:
1572 case glslang::EOpConstructI64Vec3:
1573 case glslang::EOpConstructI64Vec4:
1574 case glslang::EOpConstructUint64:
1575 case glslang::EOpConstructU64Vec2:
1576 case glslang::EOpConstructU64Vec3:
1577 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001578 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001579 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001580 {
1581 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001582 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001583 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001584 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001585 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001586 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001587 std::vector<spv::Id> constituents;
1588 for (int c = 0; c < (int)arguments.size(); ++c)
1589 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001590 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001591 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001592 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001593 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001594 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001595
1596 builder.clearAccessChain();
1597 builder.setAccessChainRValue(constructed);
1598
1599 return false;
1600 }
1601
1602 // These six are component-wise compares with component-wise results.
1603 // Forward on to createBinaryOperation(), requesting a vector result.
1604 case glslang::EOpLessThan:
1605 case glslang::EOpGreaterThan:
1606 case glslang::EOpLessThanEqual:
1607 case glslang::EOpGreaterThanEqual:
1608 case glslang::EOpVectorEqual:
1609 case glslang::EOpVectorNotEqual:
1610 {
1611 // Map the operation to a binary
1612 binOp = node->getOp();
1613 reduceComparison = false;
1614 switch (node->getOp()) {
1615 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1616 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1617 default: binOp = node->getOp(); break;
1618 }
1619
1620 break;
1621 }
1622 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001623 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001624 binOp = glslang::EOpMul;
1625 break;
1626 case glslang::EOpOuterProduct:
1627 // two vectors multiplied to make a matrix
1628 binOp = glslang::EOpOuterProduct;
1629 break;
1630 case glslang::EOpDot:
1631 {
qining25262b32016-05-06 17:25:16 -04001632 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001633 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001634 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001635 binOp = glslang::EOpMul;
1636 break;
1637 }
1638 case glslang::EOpMod:
1639 // when an aggregate, this is the floating-point mod built-in function,
1640 // which can be emitted by the one in createBinaryOperation()
1641 binOp = glslang::EOpMod;
1642 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001643 case glslang::EOpEmitVertex:
1644 case glslang::EOpEndPrimitive:
1645 case glslang::EOpBarrier:
1646 case glslang::EOpMemoryBarrier:
1647 case glslang::EOpMemoryBarrierAtomicCounter:
1648 case glslang::EOpMemoryBarrierBuffer:
1649 case glslang::EOpMemoryBarrierImage:
1650 case glslang::EOpMemoryBarrierShared:
1651 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001652 case glslang::EOpAllMemoryBarrierWithGroupSync:
1653 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1654 case glslang::EOpWorkgroupMemoryBarrier:
1655 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001656 noReturnValue = true;
1657 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1658 break;
1659
John Kessenich426394d2015-07-23 10:22:48 -06001660 case glslang::EOpAtomicAdd:
1661 case glslang::EOpAtomicMin:
1662 case glslang::EOpAtomicMax:
1663 case glslang::EOpAtomicAnd:
1664 case glslang::EOpAtomicOr:
1665 case glslang::EOpAtomicXor:
1666 case glslang::EOpAtomicExchange:
1667 case glslang::EOpAtomicCompSwap:
1668 atomic = true;
1669 break;
1670
John Kessenich140f3df2015-06-26 16:58:36 -06001671 default:
1672 break;
1673 }
1674
1675 //
1676 // See if it maps to a regular operation.
1677 //
John Kessenich140f3df2015-06-26 16:58:36 -06001678 if (binOp != glslang::EOpNull) {
1679 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1680 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1681 assert(left && right);
1682
1683 builder.clearAccessChain();
1684 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001685 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001686
1687 builder.clearAccessChain();
1688 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001689 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001690
qining25262b32016-05-06 17:25:16 -04001691 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001692 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001693 left->getType().getBasicType(), reduceComparison);
1694
1695 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001696 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001697 builder.clearAccessChain();
1698 builder.setAccessChainRValue(result);
1699
1700 return false;
1701 }
1702
John Kessenich426394d2015-07-23 10:22:48 -06001703 //
1704 // Create the list of operands.
1705 //
John Kessenich140f3df2015-06-26 16:58:36 -06001706 glslang::TIntermSequence& glslangOperands = node->getSequence();
1707 std::vector<spv::Id> operands;
1708 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001709 // special case l-value operands; there are just a few
1710 bool lvalue = false;
1711 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001712 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001713 case glslang::EOpModf:
1714 if (arg == 1)
1715 lvalue = true;
1716 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001717 case glslang::EOpInterpolateAtSample:
1718 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001719#ifdef AMD_EXTENSIONS
1720 case glslang::EOpInterpolateAtVertex:
1721#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001722 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001723 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001724
1725 // Does it need a swizzle inversion? If so, evaluation is inverted;
1726 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001727 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001728 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1729 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1730 }
Rex Xu7a26c172015-12-08 17:12:09 +08001731 break;
Rex Xud4782c12015-09-06 16:30:11 +08001732 case glslang::EOpAtomicAdd:
1733 case glslang::EOpAtomicMin:
1734 case glslang::EOpAtomicMax:
1735 case glslang::EOpAtomicAnd:
1736 case glslang::EOpAtomicOr:
1737 case glslang::EOpAtomicXor:
1738 case glslang::EOpAtomicExchange:
1739 case glslang::EOpAtomicCompSwap:
1740 if (arg == 0)
1741 lvalue = true;
1742 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001743 case glslang::EOpAddCarry:
1744 case glslang::EOpSubBorrow:
1745 if (arg == 2)
1746 lvalue = true;
1747 break;
1748 case glslang::EOpUMulExtended:
1749 case glslang::EOpIMulExtended:
1750 if (arg >= 2)
1751 lvalue = true;
1752 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001753 default:
1754 break;
1755 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001756 builder.clearAccessChain();
1757 if (invertedType != spv::NoType && arg == 0)
1758 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1759 else
1760 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001761 if (lvalue)
1762 operands.push_back(builder.accessChainGetLValue());
1763 else
John Kessenich32cfd492016-02-02 12:37:46 -07001764 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001765 }
John Kessenich426394d2015-07-23 10:22:48 -06001766
1767 if (atomic) {
1768 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001769 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001770 } else {
1771 // Pass through to generic operations.
1772 switch (glslangOperands.size()) {
1773 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001774 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001775 break;
1776 case 1:
qining25262b32016-05-06 17:25:16 -04001777 result = createUnaryOperation(
1778 node->getOp(), precision,
1779 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001780 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001781 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001782 break;
1783 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001784 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001785 break;
1786 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001787 if (invertedType)
1788 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001789 }
1790
1791 if (noReturnValue)
1792 return false;
1793
1794 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001795 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001796 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001797 } else {
1798 builder.clearAccessChain();
1799 builder.setAccessChainRValue(result);
1800 return false;
1801 }
1802}
1803
John Kessenich433e9ff2017-01-26 20:31:11 -07001804// This path handles both if-then-else and ?:
1805// The if-then-else has a node type of void, while
1806// ?: has either a void or a non-void node type
1807//
1808// Leaving the result, when not void:
1809// GLSL only has r-values as the result of a :?, but
1810// if we have an l-value, that can be more efficient if it will
1811// become the base of a complex r-value expression, because the
1812// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001813bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1814{
John Kessenich433e9ff2017-01-26 20:31:11 -07001815 // See if it simple and safe to generate OpSelect instead of using control flow.
1816 // Crucially, side effects must be avoided, and there are performance trade-offs.
1817 // Return true if good idea (and safe) for OpSelect, false otherwise.
1818 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001819 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1820 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001821 return false;
1822
1823 if (node->getTrueBlock() == nullptr ||
1824 node->getFalseBlock() == nullptr)
1825 return false;
1826
1827 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1828 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1829
1830 // return true if a single operand to ? : is okay for OpSelect
1831 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001832 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001833 };
1834
1835 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1836 operandOkay(node->getFalseBlock()->getAsTyped());
1837 };
1838
1839 // Emit OpSelect for this selection.
1840 const auto handleAsOpSelect = [&]() {
1841 node->getCondition()->traverse(this);
1842 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1843 node->getTrueBlock()->traverse(this);
1844 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1845 node->getFalseBlock()->traverse(this);
1846 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1847
John Kesseniche434ad92017-03-30 10:09:28 -06001848 // smear condition to vector, if necessary (AST is always scalar)
1849 if (builder.isVector(trueValue))
1850 condition = builder.smearScalar(spv::NoPrecision, condition,
1851 builder.makeVectorType(builder.makeBoolType(),
1852 builder.getNumComponents(trueValue)));
1853
1854 spv::Id select = builder.createTriOp(spv::OpSelect,
1855 convertGlslangToSpvType(node->getType()), condition,
1856 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001857 builder.clearAccessChain();
1858 builder.setAccessChainRValue(select);
1859 };
1860
1861 // Try for OpSelect
1862
1863 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001864 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1865 if (node->getType().getQualifier().isSpecConstant())
1866 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1867
John Kessenich433e9ff2017-01-26 20:31:11 -07001868 handleAsOpSelect();
1869 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001870 }
1871
John Kessenich433e9ff2017-01-26 20:31:11 -07001872 // Instead, emit control flow...
1873
1874 // Don't handle results as temporaries, because there will be two names
1875 // and better to leave SSA to later passes.
1876 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1877 ? spv::NoResult
1878 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1879
John Kessenich140f3df2015-06-26 16:58:36 -06001880 // emit the condition before doing anything with selection
1881 node->getCondition()->traverse(this);
1882
1883 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001884 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001885
John Kessenich433e9ff2017-01-26 20:31:11 -07001886 // emit the "then" statement
1887 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001888 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001889 if (result != spv::NoResult)
1890 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001891 }
1892
John Kessenich433e9ff2017-01-26 20:31:11 -07001893 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001894 ifBuilder.makeBeginElse();
1895 // emit the "else" statement
1896 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001897 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001898 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001899 }
1900
John Kessenich433e9ff2017-01-26 20:31:11 -07001901 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001902 ifBuilder.makeEndIf();
1903
John Kessenich433e9ff2017-01-26 20:31:11 -07001904 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001905 // GLSL only has r-values as the result of a :?, but
1906 // if we have an l-value, that can be more efficient if it will
1907 // become the base of a complex r-value expression, because the
1908 // next layer copies r-values into memory to use the access-chain mechanism
1909 builder.clearAccessChain();
1910 builder.setAccessChainLValue(result);
1911 }
1912
1913 return false;
1914}
1915
1916bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1917{
1918 // emit and get the condition before doing anything with switch
1919 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001920 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001921
1922 // browse the children to sort out code segments
1923 int defaultSegment = -1;
1924 std::vector<TIntermNode*> codeSegments;
1925 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1926 std::vector<int> caseValues;
1927 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1928 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1929 TIntermNode* child = *c;
1930 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001931 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001932 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001933 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001934 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1935 } else
1936 codeSegments.push_back(child);
1937 }
1938
qining25262b32016-05-06 17:25:16 -04001939 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001940 // statements between the last case and the end of the switch statement
1941 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1942 (int)codeSegments.size() == defaultSegment)
1943 codeSegments.push_back(nullptr);
1944
1945 // make the switch statement
1946 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001947 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001948
1949 // emit all the code in the segments
1950 breakForLoop.push(false);
1951 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1952 builder.nextSwitchSegment(segmentBlocks, s);
1953 if (codeSegments[s])
1954 codeSegments[s]->traverse(this);
1955 else
1956 builder.addSwitchBreak();
1957 }
1958 breakForLoop.pop();
1959
1960 builder.endSwitch(segmentBlocks);
1961
1962 return false;
1963}
1964
1965void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1966{
1967 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001968 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001969
1970 builder.clearAccessChain();
1971 builder.setAccessChainRValue(constant);
1972}
1973
1974bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1975{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001976 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001977 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06001978
1979 // Loop control:
1980 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
1981
1982 // TODO: dependency length
1983
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001984 // Spec requires back edges to target header blocks, and every header block
1985 // must dominate its merge block. Make a header block first to ensure these
1986 // conditions are met. By definition, it will contain OpLoopMerge, followed
1987 // by a block-ending branch. But we don't want to put any other body/test
1988 // instructions in it, since the body/test may have arbitrary instructions,
1989 // including merges of its own.
1990 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06001991 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001992 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001993 spv::Block& test = builder.makeNewBlock();
1994 builder.createBranch(&test);
1995
1996 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001997 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001998 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001999 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002000 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2001
2002 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002003 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002004 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002005 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002006 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002007 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002008
2009 builder.setBuildPoint(&blocks.continue_target);
2010 if (node->getTerminal())
2011 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002012 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002013 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002014 builder.createBranch(&blocks.body);
2015
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002016 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002017 builder.setBuildPoint(&blocks.body);
2018 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002019 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002020 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002021 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002022
2023 builder.setBuildPoint(&blocks.continue_target);
2024 if (node->getTerminal())
2025 node->getTerminal()->traverse(this);
2026 if (node->getTest()) {
2027 node->getTest()->traverse(this);
2028 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002029 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002030 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002031 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002032 // TODO: unless there was a break/return/discard instruction
2033 // somewhere in the body, this is an infinite loop, so we should
2034 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002035 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002036 }
John Kessenich140f3df2015-06-26 16:58:36 -06002037 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002038 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002039 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002040 return false;
2041}
2042
2043bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2044{
2045 if (node->getExpression())
2046 node->getExpression()->traverse(this);
2047
2048 switch (node->getFlowOp()) {
2049 case glslang::EOpKill:
2050 builder.makeDiscard();
2051 break;
2052 case glslang::EOpBreak:
2053 if (breakForLoop.top())
2054 builder.createLoopExit();
2055 else
2056 builder.addSwitchBreak();
2057 break;
2058 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002059 builder.createLoopContinue();
2060 break;
2061 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002062 if (node->getExpression()) {
2063 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2064 spv::Id returnId = accessChainLoad(glslangReturnType);
2065 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2066 builder.clearAccessChain();
2067 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2068 builder.setAccessChainLValue(copyId);
2069 multiTypeStore(glslangReturnType, returnId);
2070 returnId = builder.createLoad(copyId);
2071 }
2072 builder.makeReturn(false, returnId);
2073 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002074 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002075
2076 builder.clearAccessChain();
2077 break;
2078
2079 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002080 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002081 break;
2082 }
2083
2084 return false;
2085}
2086
2087spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2088{
qining25262b32016-05-06 17:25:16 -04002089 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002090 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002091 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002092 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002093 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002094 }
2095
2096 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002097 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002098 spv::Id spvType = convertGlslangToSpvType(node->getType());
2099
Rex Xuf89ad982017-04-07 23:22:33 +08002100#ifdef AMD_EXTENSIONS
2101 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16);
2102 if (contains16BitType) {
2103 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2104 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2105 builder.addCapability(spv::CapabilityStorageInputOutput16);
2106 } else if (storageClass == spv::StorageClassPushConstant) {
2107 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2108 builder.addCapability(spv::CapabilityStoragePushConstant16);
2109 } else if (storageClass == spv::StorageClassUniform) {
2110 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2111 builder.addCapability(spv::CapabilityStorageUniform16);
2112 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2113 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2114 }
2115 }
2116#endif
2117
John Kessenich140f3df2015-06-26 16:58:36 -06002118 const char* name = node->getName().c_str();
2119 if (glslang::IsAnonymous(name))
2120 name = "";
2121
2122 return builder.createVariable(storageClass, spvType, name);
2123}
2124
2125// Return type Id of the sampled type.
2126spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2127{
2128 switch (sampler.type) {
2129 case glslang::EbtFloat: return builder.makeFloatType(32);
2130 case glslang::EbtInt: return builder.makeIntType(32);
2131 case glslang::EbtUint: return builder.makeUintType(32);
2132 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002133 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002134 return builder.makeFloatType(32);
2135 }
2136}
2137
John Kessenich8c8505c2016-07-26 12:50:38 -06002138// If node is a swizzle operation, return the type that should be used if
2139// the swizzle base is first consumed by another operation, before the swizzle
2140// is applied.
2141spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2142{
John Kessenichecba76f2017-01-06 00:34:48 -07002143 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002144 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2145 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2146 else
2147 return spv::NoType;
2148}
2149
2150// When inverting a swizzle with a parent op, this function
2151// will apply the swizzle operation to a completed parent operation.
2152spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2153{
2154 std::vector<unsigned> swizzle;
2155 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2156 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2157}
2158
John Kessenich8c8505c2016-07-26 12:50:38 -06002159// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2160void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2161{
2162 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2163 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2164 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2165}
2166
John Kessenich3ac051e2015-12-20 11:29:16 -07002167// Convert from a glslang type to an SPV type, by calling into a
2168// recursive version of this function. This establishes the inherited
2169// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002170spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2171{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002172 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002173}
2174
2175// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002176// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002177// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002178spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002179{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002180 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002181
2182 switch (type.getBasicType()) {
2183 case glslang::EbtVoid:
2184 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002185 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002186 break;
2187 case glslang::EbtFloat:
2188 spvType = builder.makeFloatType(32);
2189 break;
2190 case glslang::EbtDouble:
2191 spvType = builder.makeFloatType(64);
2192 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002193#ifdef AMD_EXTENSIONS
2194 case glslang::EbtFloat16:
2195 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002196 spvType = builder.makeFloatType(16);
2197 break;
2198#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002199 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002200 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2201 // a 32-bit int where non-0 means true.
2202 if (explicitLayout != glslang::ElpNone)
2203 spvType = builder.makeUintType(32);
2204 else
2205 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002206 break;
2207 case glslang::EbtInt:
2208 spvType = builder.makeIntType(32);
2209 break;
2210 case glslang::EbtUint:
2211 spvType = builder.makeUintType(32);
2212 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002213 case glslang::EbtInt64:
2214 builder.addCapability(spv::CapabilityInt64);
2215 spvType = builder.makeIntType(64);
2216 break;
2217 case glslang::EbtUint64:
2218 builder.addCapability(spv::CapabilityInt64);
2219 spvType = builder.makeUintType(64);
2220 break;
John Kessenich426394d2015-07-23 10:22:48 -06002221 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002222 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002223 spvType = builder.makeUintType(32);
2224 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002225 case glslang::EbtSampler:
2226 {
2227 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002228 if (sampler.sampler) {
2229 // pure sampler
2230 spvType = builder.makeSamplerType();
2231 } else {
2232 // an image is present, make its type
2233 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2234 sampler.image ? 2 : 1, TranslateImageFormat(type));
2235 if (sampler.combined) {
2236 // already has both image and sampler, make the combined type
2237 spvType = builder.makeSampledImageType(spvType);
2238 }
John Kessenich55e7d112015-11-15 21:33:39 -07002239 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002240 }
John Kessenich140f3df2015-06-26 16:58:36 -06002241 break;
2242 case glslang::EbtStruct:
2243 case glslang::EbtBlock:
2244 {
2245 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002246 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002247
2248 // Try to share structs for different layouts, but not yet for other
2249 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002250 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002251 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002252 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002253 break;
2254
2255 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002256 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002257 memberRemapper[glslangMembers].resize(glslangMembers->size());
2258 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002259 }
2260 break;
2261 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002262 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002263 break;
2264 }
2265
2266 if (type.isMatrix())
2267 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2268 else {
2269 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2270 if (type.getVectorSize() > 1)
2271 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2272 }
2273
2274 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002275 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2276
John Kessenichc9a80832015-09-12 12:17:44 -06002277 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002278 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002279 // We need to decorate array strides for types needing explicit layout, except blocks.
2280 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002281 // Use a dummy glslang type for querying internal strides of
2282 // arrays of arrays, but using just a one-dimensional array.
2283 glslang::TType simpleArrayType(type, 0); // deference type of the array
2284 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2285 simpleArrayType.getArraySizes().dereference();
2286
2287 // Will compute the higher-order strides here, rather than making a whole
2288 // pile of types and doing repetitive recursion on their contents.
2289 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2290 }
John Kessenichf8842e52016-01-04 19:22:56 -07002291
2292 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002293 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002294 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002295 if (stride > 0)
2296 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002297 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002298 }
2299 } else {
2300 // single-dimensional array, and don't yet have stride
2301
John Kessenichf8842e52016-01-04 19:22:56 -07002302 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002303 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2304 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002305 }
John Kessenich31ed4832015-09-09 17:51:38 -06002306
John Kessenichc9a80832015-09-12 12:17:44 -06002307 // Do the outer dimension, which might not be known for a runtime-sized array
2308 if (type.isRuntimeSizedArray()) {
2309 spvType = builder.makeRuntimeArray(spvType);
2310 } else {
2311 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002312 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002313 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002314 if (stride > 0)
2315 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002316 }
2317
2318 return spvType;
2319}
2320
John Kessenich0e737842017-03-24 18:38:16 -06002321// TODO: this functionality should exist at a higher level, in creating the AST
2322//
2323// Identify interface members that don't have their required extension turned on.
2324//
2325bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2326{
2327 auto& extensions = glslangIntermediate->getRequestedExtensions();
2328
Rex Xubcf291a2017-03-29 23:01:36 +08002329 if (member.getFieldName() == "gl_ViewportMask" &&
2330 extensions.find("GL_NV_viewport_array2") == extensions.end())
2331 return true;
2332 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2333 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2334 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002335 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2336 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2337 return true;
2338 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2339 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2340 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002341 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2342 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2343 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002344
2345 return false;
2346};
2347
John Kessenich6090df02016-06-30 21:18:02 -06002348// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2349// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2350// Mutually recursive with convertGlslangToSpvType().
2351spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2352 const glslang::TTypeList* glslangMembers,
2353 glslang::TLayoutPacking explicitLayout,
2354 const glslang::TQualifier& qualifier)
2355{
2356 // Create a vector of struct types for SPIR-V to consume
2357 std::vector<spv::Id> spvMembers;
2358 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2359 int locationOffset = 0; // for use across struct members, when they are called recursively
2360 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2361 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2362 if (glslangMember.hiddenMember()) {
2363 ++memberDelta;
2364 if (type.getBasicType() == glslang::EbtBlock)
2365 memberRemapper[glslangMembers][i] = -1;
2366 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002367 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002368 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002369 if (filterMember(glslangMember))
2370 continue;
2371 }
John Kessenich6090df02016-06-30 21:18:02 -06002372 // modify just this child's view of the qualifier
2373 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2374 InheritQualifiers(memberQualifier, qualifier);
2375
2376 // manually inherit location; it's more complex
2377 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2378 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2379 if (qualifier.hasLocation())
2380 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2381
2382 // recurse
2383 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2384 }
2385 }
2386
2387 // Make the SPIR-V type
2388 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002389 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002390 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2391
2392 // Decorate it
2393 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2394
2395 return spvType;
2396}
2397
2398void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2399 const glslang::TTypeList* glslangMembers,
2400 glslang::TLayoutPacking explicitLayout,
2401 const glslang::TQualifier& qualifier,
2402 spv::Id spvType)
2403{
2404 // Name and decorate the non-hidden members
2405 int offset = -1;
2406 int locationOffset = 0; // for use within the members of this struct
2407 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2408 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2409 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002410 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002411 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002412 if (filterMember(glslangMember))
2413 continue;
2414 }
John Kessenich6090df02016-06-30 21:18:02 -06002415
2416 // modify just this child's view of the qualifier
2417 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2418 InheritQualifiers(memberQualifier, qualifier);
2419
2420 // using -1 above to indicate a hidden member
2421 if (member >= 0) {
2422 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2423 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2424 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2425 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002426 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2427 type.getQualifier().storage == glslang::EvqVaryingOut) {
2428 if (type.getBasicType() == glslang::EbtBlock ||
2429 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002430 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2431 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2432 }
2433 }
2434 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2435
2436 if (qualifier.storage == glslang::EvqBuffer) {
2437 std::vector<spv::Decoration> memory;
2438 TranslateMemoryDecoration(memberQualifier, memory);
2439 for (unsigned int i = 0; i < memory.size(); ++i)
2440 addMemberDecoration(spvType, member, memory[i]);
2441 }
2442
John Kessenich2f47bc92016-06-30 21:47:35 -06002443 // Compute location decoration; tricky based on whether inheritance is at play and
2444 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002445 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2446 // probably move to the linker stage of the front end proper, and just have the
2447 // answer sitting already distributed throughout the individual member locations.
2448 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002449 // Ignore member locations if the container is an array, as that's
2450 // ill-specified and decisions have been made to not allow this anyway.
2451 // The object itself must have a location, and that comes out from decorating the object,
2452 // not the type (this code decorates types).
2453 if (! type.isArray()) {
2454 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2455 // struct members should not have explicit locations
2456 assert(type.getBasicType() != glslang::EbtStruct);
2457 location = memberQualifier.layoutLocation;
2458 } else if (type.getBasicType() != glslang::EbtBlock) {
2459 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2460 // The members, and their nested types, must not themselves have Location decorations.
2461 } else if (qualifier.hasLocation()) // inheritance
2462 location = qualifier.layoutLocation + locationOffset;
2463 }
John Kessenich6090df02016-06-30 21:18:02 -06002464 if (location >= 0)
2465 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2466
John Kessenich2f47bc92016-06-30 21:47:35 -06002467 if (qualifier.hasLocation()) // track for upcoming inheritance
2468 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2469
John Kessenich6090df02016-06-30 21:18:02 -06002470 // component, XFB, others
2471 if (glslangMember.getQualifier().hasComponent())
2472 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2473 if (glslangMember.getQualifier().hasXfbOffset())
2474 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2475 else if (explicitLayout != glslang::ElpNone) {
2476 // figure out what to do with offset, which is accumulating
2477 int nextOffset;
2478 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2479 if (offset >= 0)
2480 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2481 offset = nextOffset;
2482 }
2483
2484 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2485 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2486
2487 // built-in variable decorations
2488 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002489 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002490 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002491
2492#ifdef NV_EXTENSIONS
2493 if (builtIn == spv::BuiltInLayer) {
2494 // SPV_NV_viewport_array2 extension
2495 if (glslangMember.getQualifier().layoutViewportRelative){
2496 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2497 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2498 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2499 }
2500 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2501 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2502 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2503 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2504 }
2505 }
chaocdf3956c2017-02-14 14:52:34 -08002506 if (glslangMember.getQualifier().layoutPassthrough) {
2507 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2508 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2509 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2510 }
chaoc771d89f2017-01-13 01:10:53 -08002511#endif
John Kessenich6090df02016-06-30 21:18:02 -06002512 }
2513 }
2514
2515 // Decorate the structure
2516 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002517 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002518 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2519 builder.addCapability(spv::CapabilityGeometryStreams);
2520 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2521 }
2522 if (glslangIntermediate->getXfbMode()) {
2523 builder.addCapability(spv::CapabilityTransformFeedback);
2524 if (type.getQualifier().hasXfbStride())
2525 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2526 if (type.getQualifier().hasXfbBuffer())
2527 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2528 }
2529}
2530
John Kessenich6c292d32016-02-15 20:58:50 -07002531// Turn the expression forming the array size into an id.
2532// This is not quite trivial, because of specialization constants.
2533// Sometimes, a raw constant is turned into an Id, and sometimes
2534// a specialization constant expression is.
2535spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2536{
2537 // First, see if this is sized with a node, meaning a specialization constant:
2538 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2539 if (specNode != nullptr) {
2540 builder.clearAccessChain();
2541 specNode->traverse(this);
2542 return accessChainLoad(specNode->getAsTyped()->getType());
2543 }
qining25262b32016-05-06 17:25:16 -04002544
John Kessenich6c292d32016-02-15 20:58:50 -07002545 // Otherwise, need a compile-time (front end) size, get it:
2546 int size = arraySizes.getDimSize(dim);
2547 assert(size > 0);
2548 return builder.makeUintConstant(size);
2549}
2550
John Kessenich103bef92016-02-08 21:38:15 -07002551// Wrap the builder's accessChainLoad to:
2552// - localize handling of RelaxedPrecision
2553// - use the SPIR-V inferred type instead of another conversion of the glslang type
2554// (avoids unnecessary work and possible type punning for structures)
2555// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002556spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2557{
John Kessenich103bef92016-02-08 21:38:15 -07002558 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2559 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2560
2561 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002562 if (type.getBasicType() == glslang::EbtBool) {
2563 if (builder.isScalarType(nominalTypeId)) {
2564 // Conversion for bool
2565 spv::Id boolType = builder.makeBoolType();
2566 if (nominalTypeId != boolType)
2567 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2568 } else if (builder.isVectorType(nominalTypeId)) {
2569 // Conversion for bvec
2570 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2571 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2572 if (nominalTypeId != bvecType)
2573 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2574 }
2575 }
John Kessenich103bef92016-02-08 21:38:15 -07002576
2577 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002578}
2579
Rex Xu27253232016-02-23 17:51:09 +08002580// Wrap the builder's accessChainStore to:
2581// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002582//
2583// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002584void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2585{
2586 // Need to convert to abstract types when necessary
2587 if (type.getBasicType() == glslang::EbtBool) {
2588 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2589
2590 if (builder.isScalarType(nominalTypeId)) {
2591 // Conversion for bool
2592 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002593 if (nominalTypeId != boolType) {
2594 // keep these outside arguments, for determinant order-of-evaluation
2595 spv::Id one = builder.makeUintConstant(1);
2596 spv::Id zero = builder.makeUintConstant(0);
2597 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2598 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002599 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002600 } else if (builder.isVectorType(nominalTypeId)) {
2601 // Conversion for bvec
2602 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2603 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002604 if (nominalTypeId != bvecType) {
2605 // keep these outside arguments, for determinant order-of-evaluation
2606 spv::Id one = builder.makeUintConstant(1);
2607 spv::Id zero = builder.makeUintConstant(0);
John Kessenich80f92a12017-05-19 23:00:13 -06002608 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue,
John Kessenichb6cabc42017-05-19 23:29:50 -06002609 makeSmearedConstant(one, vecSize),
2610 makeSmearedConstant(zero, vecSize));
2611 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002612 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2613 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002614 }
2615 }
2616
2617 builder.accessChainStore(rvalue);
2618}
2619
John Kessenich4bf71552016-09-02 11:20:21 -06002620// For storing when types match at the glslang level, but not might match at the
2621// SPIR-V level.
2622//
2623// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002624// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002625// as in a member-decorated way.
2626//
2627// NOTE: This function can handle any store request; if it's not special it
2628// simplifies to a simple OpStore.
2629//
2630// Implicitly uses the existing builder.accessChain as the storage target.
2631void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2632{
John Kessenichb3e24e42016-09-11 12:33:43 -06002633 // we only do the complex path here if it's an aggregate
2634 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002635 accessChainStore(type, rValue);
2636 return;
2637 }
2638
John Kessenichb3e24e42016-09-11 12:33:43 -06002639 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002640 spv::Id rType = builder.getTypeId(rValue);
2641 spv::Id lValue = builder.accessChainGetLValue();
2642 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2643 if (lType == rType) {
2644 accessChainStore(type, rValue);
2645 return;
2646 }
2647
John Kessenichb3e24e42016-09-11 12:33:43 -06002648 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002649 // where the two types were the same type in GLSL. This requires member
2650 // by member copy, recursively.
2651
John Kessenichb3e24e42016-09-11 12:33:43 -06002652 // If an array, copy element by element.
2653 if (type.isArray()) {
2654 glslang::TType glslangElementType(type, 0);
2655 spv::Id elementRType = builder.getContainedTypeId(rType);
2656 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2657 // get the source member
2658 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002659
John Kessenichb3e24e42016-09-11 12:33:43 -06002660 // set up the target storage
2661 builder.clearAccessChain();
2662 builder.setAccessChainLValue(lValue);
2663 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002664
John Kessenichb3e24e42016-09-11 12:33:43 -06002665 // store the member
2666 multiTypeStore(glslangElementType, elementRValue);
2667 }
2668 } else {
2669 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002670
John Kessenichb3e24e42016-09-11 12:33:43 -06002671 // loop over structure members
2672 const glslang::TTypeList& members = *type.getStruct();
2673 for (int m = 0; m < (int)members.size(); ++m) {
2674 const glslang::TType& glslangMemberType = *members[m].type;
2675
2676 // get the source member
2677 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2678 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2679
2680 // set up the target storage
2681 builder.clearAccessChain();
2682 builder.setAccessChainLValue(lValue);
2683 builder.accessChainPush(builder.makeIntConstant(m));
2684
2685 // store the member
2686 multiTypeStore(glslangMemberType, memberRValue);
2687 }
John Kessenich4bf71552016-09-02 11:20:21 -06002688 }
2689}
2690
John Kessenichf85e8062015-12-19 13:57:10 -07002691// Decide whether or not this type should be
2692// decorated with offsets and strides, and if so
2693// whether std140 or std430 rules should be applied.
2694glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002695{
John Kessenichf85e8062015-12-19 13:57:10 -07002696 // has to be a block
2697 if (type.getBasicType() != glslang::EbtBlock)
2698 return glslang::ElpNone;
2699
2700 // has to be a uniform or buffer block
2701 if (type.getQualifier().storage != glslang::EvqUniform &&
2702 type.getQualifier().storage != glslang::EvqBuffer)
2703 return glslang::ElpNone;
2704
2705 // return the layout to use
2706 switch (type.getQualifier().layoutPacking) {
2707 case glslang::ElpStd140:
2708 case glslang::ElpStd430:
2709 return type.getQualifier().layoutPacking;
2710 default:
2711 return glslang::ElpNone;
2712 }
John Kessenich31ed4832015-09-09 17:51:38 -06002713}
2714
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002715// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002716int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002717{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002718 int size;
John Kessenich49987892015-12-29 17:11:44 -07002719 int stride;
2720 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002721
2722 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002723}
2724
John Kessenich49987892015-12-29 17:11:44 -07002725// 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 -07002726// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002727int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002728{
John Kessenich49987892015-12-29 17:11:44 -07002729 glslang::TType elementType;
2730 elementType.shallowCopy(matrixType);
2731 elementType.clearArraySizes();
2732
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002733 int size;
John Kessenich49987892015-12-29 17:11:44 -07002734 int stride;
2735 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2736
2737 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002738}
2739
John Kessenich5e4b1242015-08-06 22:53:06 -06002740// Given a member type of a struct, realign the current offset for it, and compute
2741// the next (not yet aligned) offset for the next member, which will get aligned
2742// on the next call.
2743// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2744// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2745// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002746void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002747 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002748{
2749 // this will get a positive value when deemed necessary
2750 nextOffset = -1;
2751
John Kessenich5e4b1242015-08-06 22:53:06 -06002752 // override anything in currentOffset with user-set offset
2753 if (memberType.getQualifier().hasOffset())
2754 currentOffset = memberType.getQualifier().layoutOffset;
2755
2756 // It could be that current linker usage in glslang updated all the layoutOffset,
2757 // in which case the following code does not matter. But, that's not quite right
2758 // once cross-compilation unit GLSL validation is done, as the original user
2759 // settings are needed in layoutOffset, and then the following will come into play.
2760
John Kessenichf85e8062015-12-19 13:57:10 -07002761 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002762 if (! memberType.getQualifier().hasOffset())
2763 currentOffset = -1;
2764
2765 return;
2766 }
2767
John Kessenichf85e8062015-12-19 13:57:10 -07002768 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002769 if (currentOffset < 0)
2770 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002771
John Kessenich5e4b1242015-08-06 22:53:06 -06002772 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2773 // but possibly not yet correctly aligned.
2774
2775 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002776 int dummyStride;
2777 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002778
2779 // Adjust alignment for HLSL rules
2780 if (glslangIntermediate->usingHlslOFfsets() &&
2781 ! memberType.isArray() && memberType.isVector()) {
2782 int dummySize;
2783 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2784 if (componentAlignment <= 4)
2785 memberAlignment = componentAlignment;
2786 }
2787
2788 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002789 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002790
2791 // Bump up to vec4 if there is a bad straddle
2792 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2793 glslang::RoundToPow2(currentOffset, 16);
2794
John Kessenich5e4b1242015-08-06 22:53:06 -06002795 nextOffset = currentOffset + memberSize;
2796}
2797
David Netoa901ffe2016-06-08 14:11:40 +01002798void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002799{
David Netoa901ffe2016-06-08 14:11:40 +01002800 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2801 switch (glslangBuiltIn)
2802 {
2803 case glslang::EbvClipDistance:
2804 case glslang::EbvCullDistance:
2805 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002806#ifdef NV_EXTENSIONS
2807 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002808 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002809 case glslang::EbvViewportMaskNV:
2810 case glslang::EbvSecondaryPositionNV:
2811 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002812 case glslang::EbvPositionPerViewNV:
2813 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002814#endif
David Netoa901ffe2016-06-08 14:11:40 +01002815 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2816 // Alternately, we could just call this for any glslang built-in, since the
2817 // capability already guards against duplicates.
2818 TranslateBuiltInDecoration(glslangBuiltIn, false);
2819 break;
2820 default:
2821 // Capabilities were already generated when the struct was declared.
2822 break;
2823 }
John Kessenichebb50532016-05-16 19:22:05 -06002824}
2825
John Kessenich6fccb3c2016-09-19 16:01:41 -06002826bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002827{
John Kessenicheee9d532016-09-19 18:09:30 -06002828 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002829}
2830
2831// Make all the functions, skeletally, without actually visiting their bodies.
2832void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2833{
2834 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2835 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002836 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002837 continue;
2838
2839 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002840 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002841 //
qining25262b32016-05-06 17:25:16 -04002842 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002843 // function. What it is an address of varies:
2844 //
John Kessenich4bf71552016-09-02 11:20:21 -06002845 // - "in" parameters not marked as "const" can be written to without modifying the calling
2846 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002847 //
2848 // - "const in" parameters can just be the r-value, as no writes need occur.
2849 //
John Kessenich4bf71552016-09-02 11:20:21 -06002850 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2851 // 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 -06002852
2853 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002854 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002855 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2856
John Kessenich37789792017-03-21 23:56:40 -06002857 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName;
2858
John Kessenich140f3df2015-06-26 16:58:36 -06002859 for (int p = 0; p < (int)parameters.size(); ++p) {
2860 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2861 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002862 // can we pass by reference?
2863 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002864 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002865 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002866 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06002867 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002868 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002869 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2870 else
John Kessenich4bf71552016-09-02 11:20:21 -06002871 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002872 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002873 paramTypes.push_back(typeId);
2874 }
2875
2876 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002877 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2878 convertGlslangToSpvType(glslFunction->getType()),
2879 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002880 if (implicitThis)
2881 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002882
2883 // Track function to emit/call later
2884 functionMap[glslFunction->getName().c_str()] = function;
2885
2886 // Set the parameter id's
2887 for (int p = 0; p < (int)parameters.size(); ++p) {
2888 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2889 // give a name too
2890 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2891 }
2892 }
2893}
2894
2895// Process all the initializers, while skipping the functions and link objects
2896void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2897{
2898 builder.setBuildPoint(shaderEntry->getLastBlock());
2899 for (int i = 0; i < (int)initializers.size(); ++i) {
2900 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2901 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2902
2903 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002904 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002905 initializer->traverse(this);
2906 }
2907 }
2908}
2909
2910// Process all the functions, while skipping initializers.
2911void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2912{
2913 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2914 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002915 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002916 node->traverse(this);
2917 }
2918}
2919
2920void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2921{
qining25262b32016-05-06 17:25:16 -04002922 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002923 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002924 currentFunction = functionMap[node->getName().c_str()];
2925 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002926 builder.setBuildPoint(functionBlock);
2927}
2928
Rex Xu04db3f52015-09-16 11:44:02 +08002929void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002930{
Rex Xufc618912015-09-09 16:42:49 +08002931 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002932
2933 glslang::TSampler sampler = {};
2934 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002935 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002936 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2937 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2938 }
2939
John Kessenich140f3df2015-06-26 16:58:36 -06002940 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2941 builder.clearAccessChain();
2942 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002943
2944 // Special case l-value operands
2945 bool lvalue = false;
2946 switch (node.getOp()) {
2947 case glslang::EOpImageAtomicAdd:
2948 case glslang::EOpImageAtomicMin:
2949 case glslang::EOpImageAtomicMax:
2950 case glslang::EOpImageAtomicAnd:
2951 case glslang::EOpImageAtomicOr:
2952 case glslang::EOpImageAtomicXor:
2953 case glslang::EOpImageAtomicExchange:
2954 case glslang::EOpImageAtomicCompSwap:
2955 if (i == 0)
2956 lvalue = true;
2957 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002958 case glslang::EOpSparseImageLoad:
2959 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2960 lvalue = true;
2961 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002962 case glslang::EOpSparseTexture:
2963 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2964 lvalue = true;
2965 break;
2966 case glslang::EOpSparseTextureClamp:
2967 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2968 lvalue = true;
2969 break;
2970 case glslang::EOpSparseTextureLod:
2971 case glslang::EOpSparseTextureOffset:
2972 if (i == 3)
2973 lvalue = true;
2974 break;
2975 case glslang::EOpSparseTextureFetch:
2976 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2977 lvalue = true;
2978 break;
2979 case glslang::EOpSparseTextureFetchOffset:
2980 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2981 lvalue = true;
2982 break;
2983 case glslang::EOpSparseTextureLodOffset:
2984 case glslang::EOpSparseTextureGrad:
2985 case glslang::EOpSparseTextureOffsetClamp:
2986 if (i == 4)
2987 lvalue = true;
2988 break;
2989 case glslang::EOpSparseTextureGradOffset:
2990 case glslang::EOpSparseTextureGradClamp:
2991 if (i == 5)
2992 lvalue = true;
2993 break;
2994 case glslang::EOpSparseTextureGradOffsetClamp:
2995 if (i == 6)
2996 lvalue = true;
2997 break;
2998 case glslang::EOpSparseTextureGather:
2999 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3000 lvalue = true;
3001 break;
3002 case glslang::EOpSparseTextureGatherOffset:
3003 case glslang::EOpSparseTextureGatherOffsets:
3004 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3005 lvalue = true;
3006 break;
Rex Xufc618912015-09-09 16:42:49 +08003007 default:
3008 break;
3009 }
3010
Rex Xu6b86d492015-09-16 17:48:22 +08003011 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003012 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003013 else
John Kessenich32cfd492016-02-02 12:37:46 -07003014 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003015 }
3016}
3017
John Kessenichfc51d282015-08-19 13:34:18 -06003018void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003019{
John Kessenichfc51d282015-08-19 13:34:18 -06003020 builder.clearAccessChain();
3021 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003022 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003023}
John Kessenich140f3df2015-06-26 16:58:36 -06003024
John Kessenichfc51d282015-08-19 13:34:18 -06003025spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3026{
Rex Xufc618912015-09-09 16:42:49 +08003027 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06003028 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003029 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003030 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003031
John Kessenichfc51d282015-08-19 13:34:18 -06003032 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003033 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3034 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3035 std::vector<spv::Id> arguments;
3036 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003037 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003038 else
3039 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003040 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003041
3042 spv::Builder::TextureParameters params = { };
3043 params.sampler = arguments[0];
3044
Rex Xu04db3f52015-09-16 11:44:02 +08003045 glslang::TCrackedTextureOp cracked;
3046 node->crackTexture(sampler, cracked);
3047
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003048 const bool isUnsignedResult =
3049 node->getType().getBasicType() == glslang::EbtUint64 ||
3050 node->getType().getBasicType() == glslang::EbtUint;
3051
John Kessenichfc51d282015-08-19 13:34:18 -06003052 // Check for queries
3053 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003054 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3055 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003056 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003057
John Kessenichfc51d282015-08-19 13:34:18 -06003058 switch (node->getOp()) {
3059 case glslang::EOpImageQuerySize:
3060 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003061 if (arguments.size() > 1) {
3062 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003063 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003064 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003065 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003066 case glslang::EOpImageQuerySamples:
3067 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003068 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003069 case glslang::EOpTextureQueryLod:
3070 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003071 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003072 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003073 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003074 case glslang::EOpSparseTexelsResident:
3075 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003076 default:
3077 assert(0);
3078 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003079 }
John Kessenich140f3df2015-06-26 16:58:36 -06003080 }
3081
Rex Xufc618912015-09-09 16:42:49 +08003082 // Check for image functions other than queries
3083 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003084 std::vector<spv::Id> operands;
3085 auto opIt = arguments.begin();
3086 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003087
3088 // Handle subpass operations
3089 // TODO: GLSL should change to have the "MS" only on the type rather than the
3090 // built-in function.
3091 if (cracked.subpass) {
3092 // add on the (0,0) coordinate
3093 spv::Id zero = builder.makeIntConstant(0);
3094 std::vector<spv::Id> comps;
3095 comps.push_back(zero);
3096 comps.push_back(zero);
3097 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3098 if (sampler.ms) {
3099 operands.push_back(spv::ImageOperandsSampleMask);
3100 operands.push_back(*(opIt++));
3101 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003102 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003103 }
3104
John Kessenich56bab042015-09-16 10:54:31 -06003105 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003106 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003107 if (sampler.ms) {
3108 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003109 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003110 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003111 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3112 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003113 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003114 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003115 if (sampler.ms) {
3116 operands.push_back(*(opIt + 1));
3117 operands.push_back(spv::ImageOperandsSampleMask);
3118 operands.push_back(*opIt);
3119 } else
3120 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003121 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003122 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3123 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003124 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003125 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3126 builder.addCapability(spv::CapabilitySparseResidency);
3127 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3128 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3129
3130 if (sampler.ms) {
3131 operands.push_back(spv::ImageOperandsSampleMask);
3132 operands.push_back(*opIt++);
3133 }
3134
3135 // Create the return type that was a special structure
3136 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003137 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003138 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3139 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3140
3141 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3142
3143 // Decode the return type
3144 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3145 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003146 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003147 // Process image atomic operations
3148
3149 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3150 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003151 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003152
John Kessenich8c8505c2016-07-26 12:50:38 -06003153 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003154 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003155
3156 std::vector<spv::Id> operands;
3157 operands.push_back(pointer);
3158 for (; opIt != arguments.end(); ++opIt)
3159 operands.push_back(*opIt);
3160
John Kessenich8c8505c2016-07-26 12:50:38 -06003161 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003162 }
3163 }
3164
3165 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003166 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003167 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3168
John Kessenichfc51d282015-08-19 13:34:18 -06003169 // check for bias argument
3170 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003171 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003172 int nonBiasArgCount = 2;
3173 if (cracked.offset)
3174 ++nonBiasArgCount;
3175 if (cracked.grad)
3176 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003177 if (cracked.lodClamp)
3178 ++nonBiasArgCount;
3179 if (sparse)
3180 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003181
3182 if ((int)arguments.size() > nonBiasArgCount)
3183 bias = true;
3184 }
3185
John Kessenicha5c33d62016-06-02 23:45:21 -06003186 // See if the sampler param should really be just the SPV image part
3187 if (cracked.fetch) {
3188 // a fetch needs to have the image extracted first
3189 if (builder.isSampledImage(params.sampler))
3190 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3191 }
3192
John Kessenichfc51d282015-08-19 13:34:18 -06003193 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003194
John Kessenichfc51d282015-08-19 13:34:18 -06003195 params.coords = arguments[1];
3196 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003197 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003198
3199 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003200 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003201 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003202 ++extraArgs;
3203 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003204 params.Dref = arguments[2];
3205 ++extraArgs;
3206 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003207 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003208 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003209 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003210 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003211 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003212 dRefComp = builder.getNumComponents(params.coords) - 1;
3213 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003214 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3215 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003216
3217 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003218 if (cracked.lod) {
3219 params.lod = arguments[2];
3220 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003221 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3222 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3223 noImplicitLod = true;
3224 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003225
3226 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003227 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003228 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003229 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003230 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003231
3232 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003233 if (cracked.grad) {
3234 params.gradX = arguments[2 + extraArgs];
3235 params.gradY = arguments[3 + extraArgs];
3236 extraArgs += 2;
3237 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003238
3239 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003240 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003241 params.offset = arguments[2 + extraArgs];
3242 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003243 } else if (cracked.offsets) {
3244 params.offsets = arguments[2 + extraArgs];
3245 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003246 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003247
3248 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003249 if (cracked.lodClamp) {
3250 params.lodClamp = arguments[2 + extraArgs];
3251 ++extraArgs;
3252 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003253
3254 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003255 if (sparse) {
3256 params.texelOut = arguments[2 + extraArgs];
3257 ++extraArgs;
3258 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003259
3260 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003261 if (bias) {
3262 params.bias = arguments[2 + extraArgs];
3263 ++extraArgs;
3264 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003265
3266 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003267 if (cracked.gather && ! sampler.shadow) {
3268 // default component is 0, if missing, otherwise an argument
3269 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003270 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003271 ++extraArgs;
3272 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003273 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003274 }
3275 }
John Kessenichfc51d282015-08-19 13:34:18 -06003276
John Kessenich65336482016-06-16 14:06:26 -06003277 // projective component (might not to move)
3278 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3279 // are divided by the last component of P."
3280 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3281 // unused components will appear after all used components."
3282 if (cracked.proj) {
3283 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3284 int projTargetComp;
3285 switch (sampler.dim) {
3286 case glslang::Esd1D: projTargetComp = 1; break;
3287 case glslang::Esd2D: projTargetComp = 2; break;
3288 case glslang::EsdRect: projTargetComp = 2; break;
3289 default: projTargetComp = projSourceComp; break;
3290 }
3291 // copy the projective coordinate if we have to
3292 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003293 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003294 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3295 projSourceComp);
3296 params.coords = builder.createCompositeInsert(projComp, params.coords,
3297 builder.getTypeId(params.coords), projTargetComp);
3298 }
3299 }
3300
John Kessenich8c8505c2016-07-26 12:50:38 -06003301 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003302}
3303
3304spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3305{
3306 // Grab the function's pointer from the previously created function
3307 spv::Function* function = functionMap[node->getName().c_str()];
3308 if (! function)
3309 return 0;
3310
3311 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3312 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3313
3314 // See comments in makeFunctions() for details about the semantics for parameter passing.
3315 //
3316 // These imply we need a four step process:
3317 // 1. Evaluate the arguments
3318 // 2. Allocate and make copies of in, out, and inout arguments
3319 // 3. Make the call
3320 // 4. Copy back the results
3321
3322 // 1. Evaluate the arguments
3323 std::vector<spv::Builder::AccessChain> lValues;
3324 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003325 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003326 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003327 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003328 // build l-value
3329 builder.clearAccessChain();
3330 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003331 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003332 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003333 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003334 // save l-value
3335 lValues.push_back(builder.getAccessChain());
3336 } else {
3337 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003338 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003339 }
3340 }
3341
3342 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3343 // copy the original into that space.
3344 //
3345 // Also, build up the list of actual arguments to pass in for the call
3346 int lValueCount = 0;
3347 int rValueCount = 0;
3348 std::vector<spv::Id> spvArgs;
3349 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003350 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003351 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003352 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003353 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3354 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003355 builder.setAccessChain(lValues[lValueCount]);
3356 arg = builder.accessChainGetLValue();
3357 ++lValueCount;
3358 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003359 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003360 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3361 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3362 // need to copy the input into output space
3363 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003364 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003365 builder.clearAccessChain();
3366 builder.setAccessChainLValue(arg);
3367 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003368 }
3369 ++lValueCount;
3370 } else {
3371 arg = rValues[rValueCount];
3372 ++rValueCount;
3373 }
3374 spvArgs.push_back(arg);
3375 }
3376
3377 // 3. Make the call.
3378 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003379 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003380
3381 // 4. Copy back out an "out" arguments.
3382 lValueCount = 0;
3383 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003384 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003385 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3386 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3387 spv::Id copy = builder.createLoad(spvArgs[a]);
3388 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003389 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003390 }
3391 ++lValueCount;
3392 }
3393 }
3394
3395 return result;
3396}
3397
3398// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003399spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3400 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003401 spv::Id typeId, spv::Id left, spv::Id right,
3402 glslang::TBasicType typeProxy, bool reduceComparison)
3403{
Rex Xu8ff43de2016-04-22 16:51:45 +08003404 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003405#ifdef AMD_EXTENSIONS
3406 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3407#else
John Kessenich140f3df2015-06-26 16:58:36 -06003408 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003409#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003410 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003411
3412 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003413 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003414 bool comparison = false;
3415
3416 switch (op) {
3417 case glslang::EOpAdd:
3418 case glslang::EOpAddAssign:
3419 if (isFloat)
3420 binOp = spv::OpFAdd;
3421 else
3422 binOp = spv::OpIAdd;
3423 break;
3424 case glslang::EOpSub:
3425 case glslang::EOpSubAssign:
3426 if (isFloat)
3427 binOp = spv::OpFSub;
3428 else
3429 binOp = spv::OpISub;
3430 break;
3431 case glslang::EOpMul:
3432 case glslang::EOpMulAssign:
3433 if (isFloat)
3434 binOp = spv::OpFMul;
3435 else
3436 binOp = spv::OpIMul;
3437 break;
3438 case glslang::EOpVectorTimesScalar:
3439 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003440 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003441 if (builder.isVector(right))
3442 std::swap(left, right);
3443 assert(builder.isScalar(right));
3444 needMatchingVectors = false;
3445 binOp = spv::OpVectorTimesScalar;
3446 } else
3447 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003448 break;
3449 case glslang::EOpVectorTimesMatrix:
3450 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003451 binOp = spv::OpVectorTimesMatrix;
3452 break;
3453 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003454 binOp = spv::OpMatrixTimesVector;
3455 break;
3456 case glslang::EOpMatrixTimesScalar:
3457 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003458 binOp = spv::OpMatrixTimesScalar;
3459 break;
3460 case glslang::EOpMatrixTimesMatrix:
3461 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003462 binOp = spv::OpMatrixTimesMatrix;
3463 break;
3464 case glslang::EOpOuterProduct:
3465 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003466 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003467 break;
3468
3469 case glslang::EOpDiv:
3470 case glslang::EOpDivAssign:
3471 if (isFloat)
3472 binOp = spv::OpFDiv;
3473 else if (isUnsigned)
3474 binOp = spv::OpUDiv;
3475 else
3476 binOp = spv::OpSDiv;
3477 break;
3478 case glslang::EOpMod:
3479 case glslang::EOpModAssign:
3480 if (isFloat)
3481 binOp = spv::OpFMod;
3482 else if (isUnsigned)
3483 binOp = spv::OpUMod;
3484 else
3485 binOp = spv::OpSMod;
3486 break;
3487 case glslang::EOpRightShift:
3488 case glslang::EOpRightShiftAssign:
3489 if (isUnsigned)
3490 binOp = spv::OpShiftRightLogical;
3491 else
3492 binOp = spv::OpShiftRightArithmetic;
3493 break;
3494 case glslang::EOpLeftShift:
3495 case glslang::EOpLeftShiftAssign:
3496 binOp = spv::OpShiftLeftLogical;
3497 break;
3498 case glslang::EOpAnd:
3499 case glslang::EOpAndAssign:
3500 binOp = spv::OpBitwiseAnd;
3501 break;
3502 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003503 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003504 binOp = spv::OpLogicalAnd;
3505 break;
3506 case glslang::EOpInclusiveOr:
3507 case glslang::EOpInclusiveOrAssign:
3508 binOp = spv::OpBitwiseOr;
3509 break;
3510 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003511 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003512 binOp = spv::OpLogicalOr;
3513 break;
3514 case glslang::EOpExclusiveOr:
3515 case glslang::EOpExclusiveOrAssign:
3516 binOp = spv::OpBitwiseXor;
3517 break;
3518 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003519 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003520 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003521 break;
3522
3523 case glslang::EOpLessThan:
3524 case glslang::EOpGreaterThan:
3525 case glslang::EOpLessThanEqual:
3526 case glslang::EOpGreaterThanEqual:
3527 case glslang::EOpEqual:
3528 case glslang::EOpNotEqual:
3529 case glslang::EOpVectorEqual:
3530 case glslang::EOpVectorNotEqual:
3531 comparison = true;
3532 break;
3533 default:
3534 break;
3535 }
3536
John Kessenich7c1aa102015-10-15 13:29:11 -06003537 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003538 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003539 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003540 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003541 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003542
3543 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003544 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003545 builder.promoteScalar(precision, left, right);
3546
qining25262b32016-05-06 17:25:16 -04003547 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3548 addDecoration(result, noContraction);
3549 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003550 }
3551
3552 if (! comparison)
3553 return 0;
3554
John Kessenich7c1aa102015-10-15 13:29:11 -06003555 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003556
John Kessenich4583b612016-08-07 19:14:22 -06003557 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3558 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003559 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003560
3561 switch (op) {
3562 case glslang::EOpLessThan:
3563 if (isFloat)
3564 binOp = spv::OpFOrdLessThan;
3565 else if (isUnsigned)
3566 binOp = spv::OpULessThan;
3567 else
3568 binOp = spv::OpSLessThan;
3569 break;
3570 case glslang::EOpGreaterThan:
3571 if (isFloat)
3572 binOp = spv::OpFOrdGreaterThan;
3573 else if (isUnsigned)
3574 binOp = spv::OpUGreaterThan;
3575 else
3576 binOp = spv::OpSGreaterThan;
3577 break;
3578 case glslang::EOpLessThanEqual:
3579 if (isFloat)
3580 binOp = spv::OpFOrdLessThanEqual;
3581 else if (isUnsigned)
3582 binOp = spv::OpULessThanEqual;
3583 else
3584 binOp = spv::OpSLessThanEqual;
3585 break;
3586 case glslang::EOpGreaterThanEqual:
3587 if (isFloat)
3588 binOp = spv::OpFOrdGreaterThanEqual;
3589 else if (isUnsigned)
3590 binOp = spv::OpUGreaterThanEqual;
3591 else
3592 binOp = spv::OpSGreaterThanEqual;
3593 break;
3594 case glslang::EOpEqual:
3595 case glslang::EOpVectorEqual:
3596 if (isFloat)
3597 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003598 else if (isBool)
3599 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003600 else
3601 binOp = spv::OpIEqual;
3602 break;
3603 case glslang::EOpNotEqual:
3604 case glslang::EOpVectorNotEqual:
3605 if (isFloat)
3606 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003607 else if (isBool)
3608 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003609 else
3610 binOp = spv::OpINotEqual;
3611 break;
3612 default:
3613 break;
3614 }
3615
qining25262b32016-05-06 17:25:16 -04003616 if (binOp != spv::OpNop) {
3617 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3618 addDecoration(result, noContraction);
3619 return builder.setPrecision(result, precision);
3620 }
John Kessenich140f3df2015-06-26 16:58:36 -06003621
3622 return 0;
3623}
3624
John Kessenich04bb8a02015-12-12 12:28:14 -07003625//
3626// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3627// These can be any of:
3628//
3629// matrix * scalar
3630// scalar * matrix
3631// matrix * matrix linear algebraic
3632// matrix * vector
3633// vector * matrix
3634// matrix * matrix componentwise
3635// matrix op matrix op in {+, -, /}
3636// matrix op scalar op in {+, -, /}
3637// scalar op matrix op in {+, -, /}
3638//
qining25262b32016-05-06 17:25:16 -04003639spv::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 -07003640{
3641 bool firstClass = true;
3642
3643 // First, handle first-class matrix operations (* and matrix/scalar)
3644 switch (op) {
3645 case spv::OpFDiv:
3646 if (builder.isMatrix(left) && builder.isScalar(right)) {
3647 // turn matrix / scalar into a multiply...
3648 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3649 op = spv::OpMatrixTimesScalar;
3650 } else
3651 firstClass = false;
3652 break;
3653 case spv::OpMatrixTimesScalar:
3654 if (builder.isMatrix(right))
3655 std::swap(left, right);
3656 assert(builder.isScalar(right));
3657 break;
3658 case spv::OpVectorTimesMatrix:
3659 assert(builder.isVector(left));
3660 assert(builder.isMatrix(right));
3661 break;
3662 case spv::OpMatrixTimesVector:
3663 assert(builder.isMatrix(left));
3664 assert(builder.isVector(right));
3665 break;
3666 case spv::OpMatrixTimesMatrix:
3667 assert(builder.isMatrix(left));
3668 assert(builder.isMatrix(right));
3669 break;
3670 default:
3671 firstClass = false;
3672 break;
3673 }
3674
qining25262b32016-05-06 17:25:16 -04003675 if (firstClass) {
3676 spv::Id result = builder.createBinOp(op, typeId, left, right);
3677 addDecoration(result, noContraction);
3678 return builder.setPrecision(result, precision);
3679 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003680
LoopDawg592860c2016-06-09 08:57:35 -06003681 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003682 // The result type of all of them is the same type as the (a) matrix operand.
3683 // The algorithm is to:
3684 // - break the matrix(es) into vectors
3685 // - smear any scalar to a vector
3686 // - do vector operations
3687 // - make a matrix out the vector results
3688 switch (op) {
3689 case spv::OpFAdd:
3690 case spv::OpFSub:
3691 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003692 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003693 case spv::OpFMul:
3694 {
3695 // one time set up...
3696 bool leftMat = builder.isMatrix(left);
3697 bool rightMat = builder.isMatrix(right);
3698 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3699 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3700 spv::Id scalarType = builder.getScalarTypeId(typeId);
3701 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3702 std::vector<spv::Id> results;
3703 spv::Id smearVec = spv::NoResult;
3704 if (builder.isScalar(left))
3705 smearVec = builder.smearScalar(precision, left, vecType);
3706 else if (builder.isScalar(right))
3707 smearVec = builder.smearScalar(precision, right, vecType);
3708
3709 // do each vector op
3710 for (unsigned int c = 0; c < numCols; ++c) {
3711 std::vector<unsigned int> indexes;
3712 indexes.push_back(c);
3713 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3714 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003715 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3716 addDecoration(result, noContraction);
3717 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003718 }
3719
3720 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003721 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003722 }
3723 default:
3724 assert(0);
3725 return spv::NoResult;
3726 }
3727}
3728
qining25262b32016-05-06 17:25:16 -04003729spv::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 -06003730{
3731 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003732 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003733 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003734 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003735#ifdef AMD_EXTENSIONS
3736 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3737#else
Rex Xu04db3f52015-09-16 11:44:02 +08003738 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003739#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003740
3741 switch (op) {
3742 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003743 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003744 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003745 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003746 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003747 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003748 unaryOp = spv::OpSNegate;
3749 break;
3750
3751 case glslang::EOpLogicalNot:
3752 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003753 unaryOp = spv::OpLogicalNot;
3754 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003755 case glslang::EOpBitwiseNot:
3756 unaryOp = spv::OpNot;
3757 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003758
John Kessenich140f3df2015-06-26 16:58:36 -06003759 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003760 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003761 break;
3762 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003763 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003764 break;
3765 case glslang::EOpTranspose:
3766 unaryOp = spv::OpTranspose;
3767 break;
3768
3769 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003770 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003771 break;
3772 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003773 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003774 break;
3775 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003776 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003777 break;
3778 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003779 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003780 break;
3781 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003782 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003783 break;
3784 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003785 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003786 break;
3787 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003788 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003789 break;
3790 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003791 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003792 break;
3793
3794 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003795 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003796 break;
3797 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003798 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003799 break;
3800 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003801 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003802 break;
3803 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003804 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003805 break;
3806 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003807 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003808 break;
3809 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003810 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003811 break;
3812
3813 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003814 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003815 break;
3816 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003817 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003818 break;
3819
3820 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003821 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003822 break;
3823 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003824 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003825 break;
3826 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003827 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003828 break;
3829 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003830 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003831 break;
3832 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003833 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003834 break;
3835 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003836 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003837 break;
3838
3839 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003840 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003841 break;
3842 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003843 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003844 break;
3845 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003846 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003847 break;
3848 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003849 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003850 break;
3851 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003852 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003853 break;
3854 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003855 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003856 break;
3857
3858 case glslang::EOpIsNan:
3859 unaryOp = spv::OpIsNan;
3860 break;
3861 case glslang::EOpIsInf:
3862 unaryOp = spv::OpIsInf;
3863 break;
LoopDawg592860c2016-06-09 08:57:35 -06003864 case glslang::EOpIsFinite:
3865 unaryOp = spv::OpIsFinite;
3866 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003867
Rex Xucbc426e2015-12-15 16:03:10 +08003868 case glslang::EOpFloatBitsToInt:
3869 case glslang::EOpFloatBitsToUint:
3870 case glslang::EOpIntBitsToFloat:
3871 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003872 case glslang::EOpDoubleBitsToInt64:
3873 case glslang::EOpDoubleBitsToUint64:
3874 case glslang::EOpInt64BitsToDouble:
3875 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003876 unaryOp = spv::OpBitcast;
3877 break;
3878
John Kessenich140f3df2015-06-26 16:58:36 -06003879 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003880 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003881 break;
3882 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003883 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003884 break;
3885 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003886 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003887 break;
3888 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003889 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003890 break;
3891 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003892 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003893 break;
3894 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003895 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003896 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003897 case glslang::EOpPackSnorm4x8:
3898 libCall = spv::GLSLstd450PackSnorm4x8;
3899 break;
3900 case glslang::EOpUnpackSnorm4x8:
3901 libCall = spv::GLSLstd450UnpackSnorm4x8;
3902 break;
3903 case glslang::EOpPackUnorm4x8:
3904 libCall = spv::GLSLstd450PackUnorm4x8;
3905 break;
3906 case glslang::EOpUnpackUnorm4x8:
3907 libCall = spv::GLSLstd450UnpackUnorm4x8;
3908 break;
3909 case glslang::EOpPackDouble2x32:
3910 libCall = spv::GLSLstd450PackDouble2x32;
3911 break;
3912 case glslang::EOpUnpackDouble2x32:
3913 libCall = spv::GLSLstd450UnpackDouble2x32;
3914 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003915
Rex Xu8ff43de2016-04-22 16:51:45 +08003916 case glslang::EOpPackInt2x32:
3917 case glslang::EOpUnpackInt2x32:
3918 case glslang::EOpPackUint2x32:
3919 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003920 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003921 break;
3922
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003923#ifdef AMD_EXTENSIONS
3924 case glslang::EOpPackFloat2x16:
3925 case glslang::EOpUnpackFloat2x16:
3926 unaryOp = spv::OpBitcast;
3927 break;
3928#endif
3929
John Kessenich140f3df2015-06-26 16:58:36 -06003930 case glslang::EOpDPdx:
3931 unaryOp = spv::OpDPdx;
3932 break;
3933 case glslang::EOpDPdy:
3934 unaryOp = spv::OpDPdy;
3935 break;
3936 case glslang::EOpFwidth:
3937 unaryOp = spv::OpFwidth;
3938 break;
3939 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003940 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003941 unaryOp = spv::OpDPdxFine;
3942 break;
3943 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003944 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003945 unaryOp = spv::OpDPdyFine;
3946 break;
3947 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003948 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003949 unaryOp = spv::OpFwidthFine;
3950 break;
3951 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003952 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003953 unaryOp = spv::OpDPdxCoarse;
3954 break;
3955 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003956 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003957 unaryOp = spv::OpDPdyCoarse;
3958 break;
3959 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003960 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003961 unaryOp = spv::OpFwidthCoarse;
3962 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003963 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003964 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003965 libCall = spv::GLSLstd450InterpolateAtCentroid;
3966 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003967 case glslang::EOpAny:
3968 unaryOp = spv::OpAny;
3969 break;
3970 case glslang::EOpAll:
3971 unaryOp = spv::OpAll;
3972 break;
3973
3974 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003975 if (isFloat)
3976 libCall = spv::GLSLstd450FAbs;
3977 else
3978 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003979 break;
3980 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003981 if (isFloat)
3982 libCall = spv::GLSLstd450FSign;
3983 else
3984 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003985 break;
3986
John Kessenichfc51d282015-08-19 13:34:18 -06003987 case glslang::EOpAtomicCounterIncrement:
3988 case glslang::EOpAtomicCounterDecrement:
3989 case glslang::EOpAtomicCounter:
3990 {
3991 // Handle all of the atomics in one place, in createAtomicOperation()
3992 std::vector<spv::Id> operands;
3993 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003994 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003995 }
3996
John Kessenichfc51d282015-08-19 13:34:18 -06003997 case glslang::EOpBitFieldReverse:
3998 unaryOp = spv::OpBitReverse;
3999 break;
4000 case glslang::EOpBitCount:
4001 unaryOp = spv::OpBitCount;
4002 break;
4003 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004004 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004005 break;
4006 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004007 if (isUnsigned)
4008 libCall = spv::GLSLstd450FindUMsb;
4009 else
4010 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004011 break;
4012
Rex Xu574ab042016-04-14 16:53:07 +08004013 case glslang::EOpBallot:
4014 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004015 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004016 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004017 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004018#ifdef AMD_EXTENSIONS
4019 case glslang::EOpMinInvocations:
4020 case glslang::EOpMaxInvocations:
4021 case glslang::EOpAddInvocations:
4022 case glslang::EOpMinInvocationsNonUniform:
4023 case glslang::EOpMaxInvocationsNonUniform:
4024 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004025 case glslang::EOpMinInvocationsInclusiveScan:
4026 case glslang::EOpMaxInvocationsInclusiveScan:
4027 case glslang::EOpAddInvocationsInclusiveScan:
4028 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4029 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4030 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4031 case glslang::EOpMinInvocationsExclusiveScan:
4032 case glslang::EOpMaxInvocationsExclusiveScan:
4033 case glslang::EOpAddInvocationsExclusiveScan:
4034 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4035 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4036 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004037#endif
Rex Xu51596642016-09-21 18:56:12 +08004038 {
4039 std::vector<spv::Id> operands;
4040 operands.push_back(operand);
4041 return createInvocationsOperation(op, typeId, operands, typeProxy);
4042 }
Rex Xu9d93a232016-05-05 12:30:44 +08004043
4044#ifdef AMD_EXTENSIONS
4045 case glslang::EOpMbcnt:
4046 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4047 libCall = spv::MbcntAMD;
4048 break;
4049
4050 case glslang::EOpCubeFaceIndex:
4051 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4052 libCall = spv::CubeFaceIndexAMD;
4053 break;
4054
4055 case glslang::EOpCubeFaceCoord:
4056 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4057 libCall = spv::CubeFaceCoordAMD;
4058 break;
4059#endif
Rex Xu338b1852016-05-05 20:38:33 +08004060
John Kessenich140f3df2015-06-26 16:58:36 -06004061 default:
4062 return 0;
4063 }
4064
4065 spv::Id id;
4066 if (libCall >= 0) {
4067 std::vector<spv::Id> args;
4068 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004069 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004070 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004071 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004072 }
John Kessenich140f3df2015-06-26 16:58:36 -06004073
qining25262b32016-05-06 17:25:16 -04004074 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004075 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004076}
4077
John Kessenich7a53f762016-01-20 11:19:27 -07004078// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004079spv::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 -07004080{
4081 // Handle unary operations vector by vector.
4082 // The result type is the same type as the original type.
4083 // The algorithm is to:
4084 // - break the matrix into vectors
4085 // - apply the operation to each vector
4086 // - make a matrix out the vector results
4087
4088 // get the types sorted out
4089 int numCols = builder.getNumColumns(operand);
4090 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004091 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4092 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004093 std::vector<spv::Id> results;
4094
4095 // do each vector op
4096 for (int c = 0; c < numCols; ++c) {
4097 std::vector<unsigned int> indexes;
4098 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004099 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4100 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4101 addDecoration(destVec, noContraction);
4102 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004103 }
4104
4105 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004106 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004107}
4108
Rex Xu73e3ce72016-04-27 18:48:17 +08004109spv::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 -06004110{
4111 spv::Op convOp = spv::OpNop;
4112 spv::Id zero = 0;
4113 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004114 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004115
4116 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4117
4118 switch (op) {
4119 case glslang::EOpConvIntToBool:
4120 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004121 case glslang::EOpConvInt64ToBool:
4122 case glslang::EOpConvUint64ToBool:
4123 zero = (op == glslang::EOpConvInt64ToBool ||
4124 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004125 zero = makeSmearedConstant(zero, vectorSize);
4126 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4127
4128 case glslang::EOpConvFloatToBool:
4129 zero = builder.makeFloatConstant(0.0F);
4130 zero = makeSmearedConstant(zero, vectorSize);
4131 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4132
4133 case glslang::EOpConvDoubleToBool:
4134 zero = builder.makeDoubleConstant(0.0);
4135 zero = makeSmearedConstant(zero, vectorSize);
4136 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4137
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004138#ifdef AMD_EXTENSIONS
4139 case glslang::EOpConvFloat16ToBool:
4140 zero = builder.makeFloat16Constant(0.0F);
4141 zero = makeSmearedConstant(zero, vectorSize);
4142 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4143#endif
4144
John Kessenich140f3df2015-06-26 16:58:36 -06004145 case glslang::EOpConvBoolToFloat:
4146 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004147 zero = builder.makeFloatConstant(0.0F);
4148 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004149 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004150
John Kessenich140f3df2015-06-26 16:58:36 -06004151 case glslang::EOpConvBoolToDouble:
4152 convOp = spv::OpSelect;
4153 zero = builder.makeDoubleConstant(0.0);
4154 one = builder.makeDoubleConstant(1.0);
4155 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004156
4157#ifdef AMD_EXTENSIONS
4158 case glslang::EOpConvBoolToFloat16:
4159 convOp = spv::OpSelect;
4160 zero = builder.makeFloat16Constant(0.0F);
4161 one = builder.makeFloat16Constant(1.0F);
4162 break;
4163#endif
4164
John Kessenich140f3df2015-06-26 16:58:36 -06004165 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004166 case glslang::EOpConvBoolToInt64:
4167 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4168 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004169 convOp = spv::OpSelect;
4170 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004171
John Kessenich140f3df2015-06-26 16:58:36 -06004172 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004173 case glslang::EOpConvBoolToUint64:
4174 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4175 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004176 convOp = spv::OpSelect;
4177 break;
4178
4179 case glslang::EOpConvIntToFloat:
4180 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004181 case glslang::EOpConvInt64ToFloat:
4182 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004183#ifdef AMD_EXTENSIONS
4184 case glslang::EOpConvIntToFloat16:
4185 case glslang::EOpConvInt64ToFloat16:
4186#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004187 convOp = spv::OpConvertSToF;
4188 break;
4189
4190 case glslang::EOpConvUintToFloat:
4191 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004192 case glslang::EOpConvUint64ToFloat:
4193 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004194#ifdef AMD_EXTENSIONS
4195 case glslang::EOpConvUintToFloat16:
4196 case glslang::EOpConvUint64ToFloat16:
4197#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004198 convOp = spv::OpConvertUToF;
4199 break;
4200
4201 case glslang::EOpConvDoubleToFloat:
4202 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004203#ifdef AMD_EXTENSIONS
4204 case glslang::EOpConvDoubleToFloat16:
4205 case glslang::EOpConvFloat16ToDouble:
4206 case glslang::EOpConvFloatToFloat16:
4207 case glslang::EOpConvFloat16ToFloat:
4208#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004209 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004210 if (builder.isMatrixType(destType))
4211 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004212 break;
4213
4214 case glslang::EOpConvFloatToInt:
4215 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004216 case glslang::EOpConvFloatToInt64:
4217 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004218#ifdef AMD_EXTENSIONS
4219 case glslang::EOpConvFloat16ToInt:
4220 case glslang::EOpConvFloat16ToInt64:
4221#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004222 convOp = spv::OpConvertFToS;
4223 break;
4224
4225 case glslang::EOpConvUintToInt:
4226 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004227 case glslang::EOpConvUint64ToInt64:
4228 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004229 if (builder.isInSpecConstCodeGenMode()) {
4230 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004231 zero = (op == glslang::EOpConvUint64ToInt64 ||
4232 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004233 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004234 // Use OpIAdd, instead of OpBitcast to do the conversion when
4235 // generating for OpSpecConstantOp instruction.
4236 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4237 }
4238 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004239 convOp = spv::OpBitcast;
4240 break;
4241
4242 case glslang::EOpConvFloatToUint:
4243 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004244 case glslang::EOpConvFloatToUint64:
4245 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004246#ifdef AMD_EXTENSIONS
4247 case glslang::EOpConvFloat16ToUint:
4248 case glslang::EOpConvFloat16ToUint64:
4249#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004250 convOp = spv::OpConvertFToU;
4251 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004252
4253 case glslang::EOpConvIntToInt64:
4254 case glslang::EOpConvInt64ToInt:
4255 convOp = spv::OpSConvert;
4256 break;
4257
4258 case glslang::EOpConvUintToUint64:
4259 case glslang::EOpConvUint64ToUint:
4260 convOp = spv::OpUConvert;
4261 break;
4262
4263 case glslang::EOpConvIntToUint64:
4264 case glslang::EOpConvInt64ToUint:
4265 case glslang::EOpConvUint64ToInt:
4266 case glslang::EOpConvUintToInt64:
4267 // OpSConvert/OpUConvert + OpBitCast
4268 switch (op) {
4269 case glslang::EOpConvIntToUint64:
4270 convOp = spv::OpSConvert;
4271 type = builder.makeIntType(64);
4272 break;
4273 case glslang::EOpConvInt64ToUint:
4274 convOp = spv::OpSConvert;
4275 type = builder.makeIntType(32);
4276 break;
4277 case glslang::EOpConvUint64ToInt:
4278 convOp = spv::OpUConvert;
4279 type = builder.makeUintType(32);
4280 break;
4281 case glslang::EOpConvUintToInt64:
4282 convOp = spv::OpUConvert;
4283 type = builder.makeUintType(64);
4284 break;
4285 default:
4286 assert(0);
4287 break;
4288 }
4289
4290 if (vectorSize > 0)
4291 type = builder.makeVectorType(type, vectorSize);
4292
4293 operand = builder.createUnaryOp(convOp, type, operand);
4294
4295 if (builder.isInSpecConstCodeGenMode()) {
4296 // Build zero scalar or vector for OpIAdd.
4297 zero = (op == glslang::EOpConvIntToUint64 ||
4298 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4299 zero = makeSmearedConstant(zero, vectorSize);
4300 // Use OpIAdd, instead of OpBitcast to do the conversion when
4301 // generating for OpSpecConstantOp instruction.
4302 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4303 }
4304 // For normal run-time conversion instruction, use OpBitcast.
4305 convOp = spv::OpBitcast;
4306 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004307 default:
4308 break;
4309 }
4310
4311 spv::Id result = 0;
4312 if (convOp == spv::OpNop)
4313 return result;
4314
4315 if (convOp == spv::OpSelect) {
4316 zero = makeSmearedConstant(zero, vectorSize);
4317 one = makeSmearedConstant(one, vectorSize);
4318 result = builder.createTriOp(convOp, destType, operand, one, zero);
4319 } else
4320 result = builder.createUnaryOp(convOp, destType, operand);
4321
John Kessenich32cfd492016-02-02 12:37:46 -07004322 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004323}
4324
4325spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4326{
4327 if (vectorSize == 0)
4328 return constant;
4329
4330 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4331 std::vector<spv::Id> components;
4332 for (int c = 0; c < vectorSize; ++c)
4333 components.push_back(constant);
4334 return builder.makeCompositeConstant(vectorTypeId, components);
4335}
4336
John Kessenich426394d2015-07-23 10:22:48 -06004337// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004338spv::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 -06004339{
4340 spv::Op opCode = spv::OpNop;
4341
4342 switch (op) {
4343 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004344 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004345 opCode = spv::OpAtomicIAdd;
4346 break;
4347 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004348 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004349 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004350 break;
4351 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004352 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004353 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004354 break;
4355 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004356 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004357 opCode = spv::OpAtomicAnd;
4358 break;
4359 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004360 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004361 opCode = spv::OpAtomicOr;
4362 break;
4363 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004364 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004365 opCode = spv::OpAtomicXor;
4366 break;
4367 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004368 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004369 opCode = spv::OpAtomicExchange;
4370 break;
4371 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004372 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004373 opCode = spv::OpAtomicCompareExchange;
4374 break;
4375 case glslang::EOpAtomicCounterIncrement:
4376 opCode = spv::OpAtomicIIncrement;
4377 break;
4378 case glslang::EOpAtomicCounterDecrement:
4379 opCode = spv::OpAtomicIDecrement;
4380 break;
4381 case glslang::EOpAtomicCounter:
4382 opCode = spv::OpAtomicLoad;
4383 break;
4384 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004385 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004386 break;
4387 }
4388
4389 // Sort out the operands
4390 // - mapping from glslang -> SPV
4391 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004392 // - compare-exchange swaps the value and comparator
4393 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004394 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4395 auto opIt = operands.begin(); // walk the glslang operands
4396 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004397 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4398 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4399 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004400 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4401 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004402 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004403 spvAtomicOperands.push_back(*(opIt + 1));
4404 spvAtomicOperands.push_back(*opIt);
4405 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004406 }
John Kessenich426394d2015-07-23 10:22:48 -06004407
John Kessenich3e60a6f2015-09-14 22:45:16 -06004408 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004409 for (; opIt != operands.end(); ++opIt)
4410 spvAtomicOperands.push_back(*opIt);
4411
4412 return builder.createOp(opCode, typeId, spvAtomicOperands);
4413}
4414
John Kessenich91cef522016-05-05 16:45:40 -06004415// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004416spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004417{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004418#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004419 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004420 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004421#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004422
Rex Xu51596642016-09-21 18:56:12 +08004423 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004424 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004425 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4426
chaocf200da82016-12-20 12:44:35 -08004427 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4428 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004429 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4430 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004431 } else if (op == glslang::EOpAnyInvocation ||
4432 op == glslang::EOpAllInvocations ||
4433 op == glslang::EOpAllInvocationsEqual) {
4434 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4435 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004436 } else {
4437 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004438#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004439 if (op == glslang::EOpMinInvocationsNonUniform ||
4440 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004441 op == glslang::EOpAddInvocationsNonUniform ||
4442 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4443 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4444 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4445 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4446 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4447 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004448 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004449#endif
Rex Xu51596642016-09-21 18:56:12 +08004450
4451 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004452#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004453 switch (op) {
4454 case glslang::EOpMinInvocations:
4455 case glslang::EOpMaxInvocations:
4456 case glslang::EOpAddInvocations:
4457 case glslang::EOpMinInvocationsNonUniform:
4458 case glslang::EOpMaxInvocationsNonUniform:
4459 case glslang::EOpAddInvocationsNonUniform:
4460 groupOperation = spv::GroupOperationReduce;
4461 spvGroupOperands.push_back(groupOperation);
4462 break;
4463 case glslang::EOpMinInvocationsInclusiveScan:
4464 case glslang::EOpMaxInvocationsInclusiveScan:
4465 case glslang::EOpAddInvocationsInclusiveScan:
4466 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4467 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4468 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4469 groupOperation = spv::GroupOperationInclusiveScan;
4470 spvGroupOperands.push_back(groupOperation);
4471 break;
4472 case glslang::EOpMinInvocationsExclusiveScan:
4473 case glslang::EOpMaxInvocationsExclusiveScan:
4474 case glslang::EOpAddInvocationsExclusiveScan:
4475 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4476 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4477 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4478 groupOperation = spv::GroupOperationExclusiveScan;
4479 spvGroupOperands.push_back(groupOperation);
4480 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004481 default:
4482 break;
Rex Xu430ef402016-10-14 17:22:23 +08004483 }
Rex Xu9d93a232016-05-05 12:30:44 +08004484#endif
Rex Xu51596642016-09-21 18:56:12 +08004485 }
4486
4487 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4488 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004489
4490 switch (op) {
4491 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004492 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004493 break;
John Kessenich91cef522016-05-05 16:45:40 -06004494 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004495 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004496 break;
John Kessenich91cef522016-05-05 16:45:40 -06004497 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004498 opCode = spv::OpSubgroupAllEqualKHR;
4499 break;
Rex Xu51596642016-09-21 18:56:12 +08004500 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004501 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004502 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004503 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004504 break;
4505 case glslang::EOpReadFirstInvocation:
4506 opCode = spv::OpSubgroupFirstInvocationKHR;
4507 break;
4508 case glslang::EOpBallot:
4509 {
4510 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4511 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4512 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4513 //
4514 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4515 //
4516 spv::Id uintType = builder.makeUintType(32);
4517 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4518 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4519
4520 std::vector<spv::Id> components;
4521 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4522 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4523
4524 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4525 return builder.createUnaryOp(spv::OpBitcast, typeId,
4526 builder.createCompositeConstruct(uvec2Type, components));
4527 }
4528
Rex Xu9d93a232016-05-05 12:30:44 +08004529#ifdef AMD_EXTENSIONS
4530 case glslang::EOpMinInvocations:
4531 case glslang::EOpMaxInvocations:
4532 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004533 case glslang::EOpMinInvocationsInclusiveScan:
4534 case glslang::EOpMaxInvocationsInclusiveScan:
4535 case glslang::EOpAddInvocationsInclusiveScan:
4536 case glslang::EOpMinInvocationsExclusiveScan:
4537 case glslang::EOpMaxInvocationsExclusiveScan:
4538 case glslang::EOpAddInvocationsExclusiveScan:
4539 if (op == glslang::EOpMinInvocations ||
4540 op == glslang::EOpMinInvocationsInclusiveScan ||
4541 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004542 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004543 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004544 else {
4545 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004546 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004547 else
Rex Xu51596642016-09-21 18:56:12 +08004548 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004549 }
Rex Xu430ef402016-10-14 17:22:23 +08004550 } else if (op == glslang::EOpMaxInvocations ||
4551 op == glslang::EOpMaxInvocationsInclusiveScan ||
4552 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004553 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004554 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004555 else {
4556 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004557 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004558 else
Rex Xu51596642016-09-21 18:56:12 +08004559 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004560 }
4561 } else {
4562 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004563 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004564 else
Rex Xu51596642016-09-21 18:56:12 +08004565 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004566 }
4567
Rex Xu2bbbe062016-08-23 15:41:05 +08004568 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004569 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004570
4571 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004572 case glslang::EOpMinInvocationsNonUniform:
4573 case glslang::EOpMaxInvocationsNonUniform:
4574 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004575 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4576 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4577 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4578 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4579 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4580 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4581 if (op == glslang::EOpMinInvocationsNonUniform ||
4582 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4583 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004584 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004585 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004586 else {
4587 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004588 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004589 else
Rex Xu51596642016-09-21 18:56:12 +08004590 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004591 }
4592 }
Rex Xu430ef402016-10-14 17:22:23 +08004593 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4594 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4595 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004596 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004597 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004598 else {
4599 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004600 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004601 else
Rex Xu51596642016-09-21 18:56:12 +08004602 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004603 }
4604 }
4605 else {
4606 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004607 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004608 else
Rex Xu51596642016-09-21 18:56:12 +08004609 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004610 }
4611
Rex Xu2bbbe062016-08-23 15:41:05 +08004612 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004613 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004614
4615 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004616#endif
John Kessenich91cef522016-05-05 16:45:40 -06004617 default:
4618 logger->missingFunctionality("invocation operation");
4619 return spv::NoResult;
4620 }
Rex Xu51596642016-09-21 18:56:12 +08004621
4622 assert(opCode != spv::OpNop);
4623 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004624}
4625
Rex Xu2bbbe062016-08-23 15:41:05 +08004626// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004627spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004628{
Rex Xub7072052016-09-26 15:53:40 +08004629#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004630 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4631 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004632 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004633 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004634 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4635 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4636 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004637#else
4638 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4639 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004640 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4641 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004642#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004643
4644 // Handle group invocation operations scalar by scalar.
4645 // The result type is the same type as the original type.
4646 // The algorithm is to:
4647 // - break the vector into scalars
4648 // - apply the operation to each scalar
4649 // - make a vector out the scalar results
4650
4651 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004652 int numComponents = builder.getNumComponents(operands[0]);
4653 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004654 std::vector<spv::Id> results;
4655
4656 // do each scalar op
4657 for (int comp = 0; comp < numComponents; ++comp) {
4658 std::vector<unsigned int> indexes;
4659 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004660 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004661 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004662 if (op == spv::OpSubgroupReadInvocationKHR) {
4663 spvGroupOperands.push_back(scalar);
4664 spvGroupOperands.push_back(operands[1]);
4665 } else if (op == spv::OpGroupBroadcast) {
4666 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004667 spvGroupOperands.push_back(scalar);
4668 spvGroupOperands.push_back(operands[1]);
4669 } else {
chaocf200da82016-12-20 12:44:35 -08004670 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004671 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004672 spvGroupOperands.push_back(scalar);
4673 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004674
Rex Xub7072052016-09-26 15:53:40 +08004675 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004676 }
4677
4678 // put the pieces together
4679 return builder.createCompositeConstruct(typeId, results);
4680}
Rex Xu2bbbe062016-08-23 15:41:05 +08004681
John Kessenich5e4b1242015-08-06 22:53:06 -06004682spv::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 -06004683{
Rex Xu8ff43de2016-04-22 16:51:45 +08004684 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004685#ifdef AMD_EXTENSIONS
4686 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4687#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004688 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004689#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004690
John Kessenich140f3df2015-06-26 16:58:36 -06004691 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004692 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004693 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004694 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004695 spv::Id typeId0 = 0;
4696 if (consumedOperands > 0)
4697 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08004698 spv::Id typeId1 = 0;
4699 if (consumedOperands > 1)
4700 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07004701 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004702
4703 switch (op) {
4704 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004705 if (isFloat)
4706 libCall = spv::GLSLstd450FMin;
4707 else if (isUnsigned)
4708 libCall = spv::GLSLstd450UMin;
4709 else
4710 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004711 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004712 break;
4713 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004714 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004715 break;
4716 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004717 if (isFloat)
4718 libCall = spv::GLSLstd450FMax;
4719 else if (isUnsigned)
4720 libCall = spv::GLSLstd450UMax;
4721 else
4722 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004723 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004724 break;
4725 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004726 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004727 break;
4728 case glslang::EOpDot:
4729 opCode = spv::OpDot;
4730 break;
4731 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004732 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004733 break;
4734
4735 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004736 if (isFloat)
4737 libCall = spv::GLSLstd450FClamp;
4738 else if (isUnsigned)
4739 libCall = spv::GLSLstd450UClamp;
4740 else
4741 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004742 builder.promoteScalar(precision, operands.front(), operands[1]);
4743 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004744 break;
4745 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004746 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4747 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004748 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004749 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004750 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004751 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004752 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004753 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004754 break;
4755 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004756 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004757 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004758 break;
4759 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004760 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004761 builder.promoteScalar(precision, operands[0], operands[2]);
4762 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004763 break;
4764
4765 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004766 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004767 break;
4768 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004769 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004770 break;
4771 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004772 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004773 break;
4774 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004775 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004776 break;
4777 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004778 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004779 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004780 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004781 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004782 libCall = spv::GLSLstd450InterpolateAtSample;
4783 break;
4784 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004785 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004786 libCall = spv::GLSLstd450InterpolateAtOffset;
4787 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004788 case glslang::EOpAddCarry:
4789 opCode = spv::OpIAddCarry;
4790 typeId = builder.makeStructResultType(typeId0, typeId0);
4791 consumedOperands = 2;
4792 break;
4793 case glslang::EOpSubBorrow:
4794 opCode = spv::OpISubBorrow;
4795 typeId = builder.makeStructResultType(typeId0, typeId0);
4796 consumedOperands = 2;
4797 break;
4798 case glslang::EOpUMulExtended:
4799 opCode = spv::OpUMulExtended;
4800 typeId = builder.makeStructResultType(typeId0, typeId0);
4801 consumedOperands = 2;
4802 break;
4803 case glslang::EOpIMulExtended:
4804 opCode = spv::OpSMulExtended;
4805 typeId = builder.makeStructResultType(typeId0, typeId0);
4806 consumedOperands = 2;
4807 break;
4808 case glslang::EOpBitfieldExtract:
4809 if (isUnsigned)
4810 opCode = spv::OpBitFieldUExtract;
4811 else
4812 opCode = spv::OpBitFieldSExtract;
4813 break;
4814 case glslang::EOpBitfieldInsert:
4815 opCode = spv::OpBitFieldInsert;
4816 break;
4817
4818 case glslang::EOpFma:
4819 libCall = spv::GLSLstd450Fma;
4820 break;
4821 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004822 {
4823 libCall = spv::GLSLstd450FrexpStruct;
4824 assert(builder.isPointerType(typeId1));
4825 typeId1 = builder.getContainedTypeId(typeId1);
4826#ifdef AMD_EXTENSIONS
4827 int width = builder.getScalarTypeWidth(typeId1);
4828#else
4829 int width = 32;
4830#endif
4831 if (builder.getNumComponents(operands[0]) == 1)
4832 frexpIntType = builder.makeIntegerType(width, true);
4833 else
4834 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
4835 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4836 consumedOperands = 1;
4837 }
John Kessenich55e7d112015-11-15 21:33:39 -07004838 break;
4839 case glslang::EOpLdexp:
4840 libCall = spv::GLSLstd450Ldexp;
4841 break;
4842
Rex Xu574ab042016-04-14 16:53:07 +08004843 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004844 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004845
Rex Xu9d93a232016-05-05 12:30:44 +08004846#ifdef AMD_EXTENSIONS
4847 case glslang::EOpSwizzleInvocations:
4848 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4849 libCall = spv::SwizzleInvocationsAMD;
4850 break;
4851 case glslang::EOpSwizzleInvocationsMasked:
4852 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4853 libCall = spv::SwizzleInvocationsMaskedAMD;
4854 break;
4855 case glslang::EOpWriteInvocation:
4856 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4857 libCall = spv::WriteInvocationAMD;
4858 break;
4859
4860 case glslang::EOpMin3:
4861 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4862 if (isFloat)
4863 libCall = spv::FMin3AMD;
4864 else {
4865 if (isUnsigned)
4866 libCall = spv::UMin3AMD;
4867 else
4868 libCall = spv::SMin3AMD;
4869 }
4870 break;
4871 case glslang::EOpMax3:
4872 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4873 if (isFloat)
4874 libCall = spv::FMax3AMD;
4875 else {
4876 if (isUnsigned)
4877 libCall = spv::UMax3AMD;
4878 else
4879 libCall = spv::SMax3AMD;
4880 }
4881 break;
4882 case glslang::EOpMid3:
4883 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4884 if (isFloat)
4885 libCall = spv::FMid3AMD;
4886 else {
4887 if (isUnsigned)
4888 libCall = spv::UMid3AMD;
4889 else
4890 libCall = spv::SMid3AMD;
4891 }
4892 break;
4893
4894 case glslang::EOpInterpolateAtVertex:
4895 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4896 libCall = spv::InterpolateAtVertexAMD;
4897 break;
4898#endif
4899
John Kessenich140f3df2015-06-26 16:58:36 -06004900 default:
4901 return 0;
4902 }
4903
4904 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004905 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004906 // Use an extended instruction from the standard library.
4907 // Construct the call arguments, without modifying the original operands vector.
4908 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4909 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004910 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004911 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004912 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004913 case 0:
4914 // should all be handled by visitAggregate and createNoArgOperation
4915 assert(0);
4916 return 0;
4917 case 1:
4918 // should all be handled by createUnaryOperation
4919 assert(0);
4920 return 0;
4921 case 2:
4922 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4923 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004924 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004925 // anything 3 or over doesn't have l-value operands, so all should be consumed
4926 assert(consumedOperands == operands.size());
4927 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004928 break;
4929 }
4930 }
4931
John Kessenich55e7d112015-11-15 21:33:39 -07004932 // Decode the return types that were structures
4933 switch (op) {
4934 case glslang::EOpAddCarry:
4935 case glslang::EOpSubBorrow:
4936 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4937 id = builder.createCompositeExtract(id, typeId0, 0);
4938 break;
4939 case glslang::EOpUMulExtended:
4940 case glslang::EOpIMulExtended:
4941 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4942 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4943 break;
4944 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004945 {
4946 assert(operands.size() == 2);
4947 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
4948 // "exp" is floating-point type (from HLSL intrinsic)
4949 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
4950 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
4951 builder.createStore(member1, operands[1]);
4952 } else
4953 // "exp" is integer type (from GLSL built-in function)
4954 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4955 id = builder.createCompositeExtract(id, typeId0, 0);
4956 }
John Kessenich55e7d112015-11-15 21:33:39 -07004957 break;
4958 default:
4959 break;
4960 }
4961
John Kessenich32cfd492016-02-02 12:37:46 -07004962 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004963}
4964
Rex Xu9d93a232016-05-05 12:30:44 +08004965// Intrinsics with no arguments (or no return value, and no precision).
4966spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004967{
4968 // TODO: get the barrier operands correct
4969
4970 switch (op) {
4971 case glslang::EOpEmitVertex:
4972 builder.createNoResultOp(spv::OpEmitVertex);
4973 return 0;
4974 case glslang::EOpEndPrimitive:
4975 builder.createNoResultOp(spv::OpEndPrimitive);
4976 return 0;
4977 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004978 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004979 return 0;
4980 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004981 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004982 return 0;
4983 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004984 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004985 return 0;
4986 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004987 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004988 return 0;
4989 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004990 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004991 return 0;
4992 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004993 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004994 return 0;
4995 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004996 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004997 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004998 case glslang::EOpAllMemoryBarrierWithGroupSync:
4999 // Control barrier with non-"None" semantic is also a memory barrier.
5000 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5001 return 0;
5002 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5003 // Control barrier with non-"None" semantic is also a memory barrier.
5004 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5005 return 0;
5006 case glslang::EOpWorkgroupMemoryBarrier:
5007 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5008 return 0;
5009 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5010 // Control barrier with non-"None" semantic is also a memory barrier.
5011 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5012 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005013#ifdef AMD_EXTENSIONS
5014 case glslang::EOpTime:
5015 {
5016 std::vector<spv::Id> args; // Dummy arguments
5017 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5018 return builder.setPrecision(id, precision);
5019 }
5020#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005021 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005022 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005023 return 0;
5024 }
5025}
5026
5027spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5028{
John Kessenich2f273362015-07-18 22:34:27 -06005029 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005030 spv::Id id;
5031 if (symbolValues.end() != iter) {
5032 id = iter->second;
5033 return id;
5034 }
5035
5036 // it was not found, create it
5037 id = createSpvVariable(symbol);
5038 symbolValues[symbol->getId()] = id;
5039
Rex Xuc884b4a2016-06-29 15:03:44 +08005040 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005041 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005042 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005043 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005044 if (symbol->getType().getQualifier().hasSpecConstantId())
5045 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005046 if (symbol->getQualifier().hasIndex())
5047 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5048 if (symbol->getQualifier().hasComponent())
5049 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5050 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005051 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005052 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005053 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005054 if (symbol->getQualifier().hasXfbBuffer())
5055 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5056 if (symbol->getQualifier().hasXfbOffset())
5057 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5058 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005059 // atomic counters use this:
5060 if (symbol->getQualifier().hasOffset())
5061 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005062 }
5063
scygan2c864272016-05-18 18:09:17 +02005064 if (symbol->getQualifier().hasLocation())
5065 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005066 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005067 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005068 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005069 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005070 }
John Kessenich140f3df2015-06-26 16:58:36 -06005071 if (symbol->getQualifier().hasSet())
5072 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005073 else if (IsDescriptorResource(symbol->getType())) {
5074 // default to 0
5075 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5076 }
John Kessenich140f3df2015-06-26 16:58:36 -06005077 if (symbol->getQualifier().hasBinding())
5078 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005079 if (symbol->getQualifier().hasAttachment())
5080 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005081 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005082 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005083 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005084 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005085 if (symbol->getQualifier().hasXfbBuffer())
5086 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5087 }
5088
Rex Xu1da878f2016-02-21 20:59:01 +08005089 if (symbol->getType().isImage()) {
5090 std::vector<spv::Decoration> memory;
5091 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5092 for (unsigned int i = 0; i < memory.size(); ++i)
5093 addDecoration(id, memory[i]);
5094 }
5095
John Kessenich140f3df2015-06-26 16:58:36 -06005096 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005097 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005098 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005099 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005100
John Kessenichecba76f2017-01-06 00:34:48 -07005101#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005102 if (builtIn == spv::BuiltInSampleMask) {
5103 spv::Decoration decoration;
5104 // GL_NV_sample_mask_override_coverage extension
5105 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005106 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005107 else
5108 decoration = (spv::Decoration)spv::DecorationMax;
5109 addDecoration(id, decoration);
5110 if (decoration != spv::DecorationMax) {
5111 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5112 }
5113 }
chaoc771d89f2017-01-13 01:10:53 -08005114 else if (builtIn == spv::BuiltInLayer) {
5115 // SPV_NV_viewport_array2 extension
5116 if (symbol->getQualifier().layoutViewportRelative)
5117 {
5118 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5119 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5120 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5121 }
5122 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5123 {
5124 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5125 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5126 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5127 }
5128 }
5129
chaoc6e5acae2016-12-20 13:28:52 -08005130 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005131 addDecoration(id, spv::DecorationPassthroughNV);
5132 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005133 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5134 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005135#endif
5136
John Kessenich140f3df2015-06-26 16:58:36 -06005137 return id;
5138}
5139
John Kessenich55e7d112015-11-15 21:33:39 -07005140// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005141void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5142{
John Kessenich4016e382016-07-15 11:53:56 -06005143 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005144 builder.addDecoration(id, dec);
5145}
5146
John Kessenich55e7d112015-11-15 21:33:39 -07005147// If 'dec' is valid, add a one-operand decoration to an object
5148void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5149{
John Kessenich4016e382016-07-15 11:53:56 -06005150 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005151 builder.addDecoration(id, dec, value);
5152}
5153
5154// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005155void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5156{
John Kessenich4016e382016-07-15 11:53:56 -06005157 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005158 builder.addMemberDecoration(id, (unsigned)member, dec);
5159}
5160
John Kessenich92187592016-02-01 13:45:25 -07005161// If 'dec' is valid, add a one-operand decoration to a struct member
5162void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5163{
John Kessenich4016e382016-07-15 11:53:56 -06005164 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005165 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5166}
5167
John Kessenich55e7d112015-11-15 21:33:39 -07005168// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005169// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005170//
5171// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5172//
5173// Recursively walk the nodes. The nodes form a tree whose leaves are
5174// regular constants, which themselves are trees that createSpvConstant()
5175// recursively walks. So, this function walks the "top" of the tree:
5176// - emit specialization constant-building instructions for specConstant
5177// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005178spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005179{
John Kessenich7cc0e282016-03-20 00:46:02 -06005180 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005181
qining4f4bb812016-04-03 23:55:17 -04005182 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005183 if (! node.getQualifier().specConstant) {
5184 // hand off to the non-spec-constant path
5185 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5186 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005187 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005188 nextConst, false);
5189 }
5190
5191 // We now know we have a specialization constant to build
5192
John Kessenichd94c0032016-05-30 19:29:40 -06005193 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005194 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5195 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5196 std::vector<spv::Id> dimConstId;
5197 for (int dim = 0; dim < 3; ++dim) {
5198 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5199 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5200 if (specConst)
5201 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5202 }
5203 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5204 }
5205
5206 // An AST node labelled as specialization constant should be a symbol node.
5207 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5208 if (auto* sn = node.getAsSymbolNode()) {
5209 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005210 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5211 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5212 // will set the builder into spec constant op instruction generating mode.
5213 sub_tree->traverse(this);
5214 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005215 } else if (auto* const_union_array = &sn->getConstArray()){
5216 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005217 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5218 builder.addName(id, sn->getName().c_str());
5219 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005220 }
5221 }
qining4f4bb812016-04-03 23:55:17 -04005222
5223 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5224 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005225 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005226 exit(1);
5227 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005228}
5229
John Kessenich140f3df2015-06-26 16:58:36 -06005230// Use 'consts' as the flattened glslang source of scalar constants to recursively
5231// build the aggregate SPIR-V constant.
5232//
5233// If there are not enough elements present in 'consts', 0 will be substituted;
5234// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5235//
qining08408382016-03-21 09:51:37 -04005236spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005237{
5238 // vector of constants for SPIR-V
5239 std::vector<spv::Id> spvConsts;
5240
5241 // Type is used for struct and array constants
5242 spv::Id typeId = convertGlslangToSpvType(glslangType);
5243
5244 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005245 glslang::TType elementType(glslangType, 0);
5246 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005247 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005248 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005249 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005250 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005251 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005252 } else if (glslangType.getStruct()) {
5253 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5254 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005255 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005256 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005257 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5258 bool zero = nextConst >= consts.size();
5259 switch (glslangType.getBasicType()) {
5260 case glslang::EbtInt:
5261 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5262 break;
5263 case glslang::EbtUint:
5264 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5265 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005266 case glslang::EbtInt64:
5267 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5268 break;
5269 case glslang::EbtUint64:
5270 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5271 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005272 case glslang::EbtFloat:
5273 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5274 break;
5275 case glslang::EbtDouble:
5276 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5277 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005278#ifdef AMD_EXTENSIONS
5279 case glslang::EbtFloat16:
5280 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5281 break;
5282#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005283 case glslang::EbtBool:
5284 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5285 break;
5286 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005287 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005288 break;
5289 }
5290 ++nextConst;
5291 }
5292 } else {
5293 // we have a non-aggregate (scalar) constant
5294 bool zero = nextConst >= consts.size();
5295 spv::Id scalar = 0;
5296 switch (glslangType.getBasicType()) {
5297 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005298 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005299 break;
5300 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005301 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005302 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005303 case glslang::EbtInt64:
5304 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5305 break;
5306 case glslang::EbtUint64:
5307 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5308 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005309 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005310 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005311 break;
5312 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005313 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005314 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005315#ifdef AMD_EXTENSIONS
5316 case glslang::EbtFloat16:
5317 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5318 break;
5319#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005320 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005321 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005322 break;
5323 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005324 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005325 break;
5326 }
5327 ++nextConst;
5328 return scalar;
5329 }
5330
5331 return builder.makeCompositeConstant(typeId, spvConsts);
5332}
5333
John Kessenich7c1aa102015-10-15 13:29:11 -06005334// Return true if the node is a constant or symbol whose reading has no
5335// non-trivial observable cost or effect.
5336bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5337{
5338 // don't know what this is
5339 if (node == nullptr)
5340 return false;
5341
5342 // a constant is safe
5343 if (node->getAsConstantUnion() != nullptr)
5344 return true;
5345
5346 // not a symbol means non-trivial
5347 if (node->getAsSymbolNode() == nullptr)
5348 return false;
5349
5350 // a symbol, depends on what's being read
5351 switch (node->getType().getQualifier().storage) {
5352 case glslang::EvqTemporary:
5353 case glslang::EvqGlobal:
5354 case glslang::EvqIn:
5355 case glslang::EvqInOut:
5356 case glslang::EvqConst:
5357 case glslang::EvqConstReadOnly:
5358 case glslang::EvqUniform:
5359 return true;
5360 default:
5361 return false;
5362 }
qining25262b32016-05-06 17:25:16 -04005363}
John Kessenich7c1aa102015-10-15 13:29:11 -06005364
5365// A node is trivial if it is a single operation with no side effects.
John Kessenich0d2b4712017-05-19 20:19:00 -06005366// Vector results seem ill-defined, currently classifying them as trivial too,
5367// to avoid scalar bool-based control-flow logic.
5368// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005369// Return true if trivial.
5370bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5371{
5372 if (node == nullptr)
5373 return false;
5374
John Kessenich0d2b4712017-05-19 20:19:00 -06005375 // count vectors as trivial
5376 if (node->getType().isVector())
5377 return true;
5378
John Kessenich7c1aa102015-10-15 13:29:11 -06005379 // symbols and constants are trivial
5380 if (isTrivialLeaf(node))
5381 return true;
5382
5383 // otherwise, it needs to be a simple operation or one or two leaf nodes
5384
5385 // not a simple operation
5386 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5387 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5388 if (binaryNode == nullptr && unaryNode == nullptr)
5389 return false;
5390
5391 // not on leaf nodes
5392 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5393 return false;
5394
5395 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5396 return false;
5397 }
5398
5399 switch (node->getAsOperator()->getOp()) {
5400 case glslang::EOpLogicalNot:
5401 case glslang::EOpConvIntToBool:
5402 case glslang::EOpConvUintToBool:
5403 case glslang::EOpConvFloatToBool:
5404 case glslang::EOpConvDoubleToBool:
5405 case glslang::EOpEqual:
5406 case glslang::EOpNotEqual:
5407 case glslang::EOpLessThan:
5408 case glslang::EOpGreaterThan:
5409 case glslang::EOpLessThanEqual:
5410 case glslang::EOpGreaterThanEqual:
5411 case glslang::EOpIndexDirect:
5412 case glslang::EOpIndexDirectStruct:
5413 case glslang::EOpLogicalXor:
5414 case glslang::EOpAny:
5415 case glslang::EOpAll:
5416 return true;
5417 default:
5418 return false;
5419 }
5420}
5421
5422// Emit short-circuiting code, where 'right' is never evaluated unless
5423// the left side is true (for &&) or false (for ||).
5424spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5425{
5426 spv::Id boolTypeId = builder.makeBoolType();
5427
5428 // emit left operand
5429 builder.clearAccessChain();
5430 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005431 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005432
5433 // Operands to accumulate OpPhi operands
5434 std::vector<spv::Id> phiOperands;
5435 // accumulate left operand's phi information
5436 phiOperands.push_back(leftId);
5437 phiOperands.push_back(builder.getBuildPoint()->getId());
5438
5439 // Make the two kinds of operation symmetric with a "!"
5440 // || => emit "if (! left) result = right"
5441 // && => emit "if ( left) result = right"
5442 //
5443 // TODO: this runtime "not" for || could be avoided by adding functionality
5444 // to 'builder' to have an "else" without an "then"
5445 if (op == glslang::EOpLogicalOr)
5446 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5447
5448 // make an "if" based on the left value
5449 spv::Builder::If ifBuilder(leftId, builder);
5450
5451 // emit right operand as the "then" part of the "if"
5452 builder.clearAccessChain();
5453 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005454 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005455
5456 // accumulate left operand's phi information
5457 phiOperands.push_back(rightId);
5458 phiOperands.push_back(builder.getBuildPoint()->getId());
5459
5460 // finish the "if"
5461 ifBuilder.makeEndIf();
5462
5463 // phi together the two results
5464 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5465}
5466
Rex Xu9d93a232016-05-05 12:30:44 +08005467// Return type Id of the imported set of extended instructions corresponds to the name.
5468// Import this set if it has not been imported yet.
5469spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5470{
5471 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5472 return extBuiltinMap[name];
5473 else {
Rex Xu51596642016-09-21 18:56:12 +08005474 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005475 spv::Id extBuiltins = builder.import(name);
5476 extBuiltinMap[name] = extBuiltins;
5477 return extBuiltins;
5478 }
5479}
5480
John Kessenich140f3df2015-06-26 16:58:36 -06005481}; // end anonymous namespace
5482
5483namespace glslang {
5484
John Kessenich68d78fd2015-07-12 19:28:10 -06005485void GetSpirvVersion(std::string& version)
5486{
John Kessenich9e55f632015-07-15 10:03:39 -06005487 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005488 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005489 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005490 version = buf;
5491}
5492
John Kessenich140f3df2015-06-26 16:58:36 -06005493// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005494void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005495{
5496 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005497 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005498 if (out.fail())
5499 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005500 for (int i = 0; i < (int)spirv.size(); ++i) {
5501 unsigned int word = spirv[i];
5502 out.write((const char*)&word, 4);
5503 }
5504 out.close();
5505}
5506
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005507// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005508void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005509{
5510 std::ofstream out;
5511 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005512 if (out.fail())
5513 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005514 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005515 if (varName != nullptr) {
5516 out << "\t #pragma once" << std::endl;
5517 out << "const uint32_t " << varName << "[] = {" << std::endl;
5518 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005519 const int WORDS_PER_LINE = 8;
5520 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5521 out << "\t";
5522 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5523 const unsigned int word = spirv[i + j];
5524 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5525 if (i + j + 1 < (int)spirv.size()) {
5526 out << ",";
5527 }
5528 }
5529 out << std::endl;
5530 }
Flavio15017db2017-02-15 14:29:33 -08005531 if (varName != nullptr) {
5532 out << "};";
5533 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005534 out.close();
5535}
5536
John Kessenich140f3df2015-06-26 16:58:36 -06005537//
5538// Set up the glslang traversal
5539//
5540void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5541{
Lei Zhang17535f72016-05-04 15:55:59 -04005542 spv::SpvBuildLogger logger;
5543 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005544}
5545
Lei Zhang17535f72016-05-04 15:55:59 -04005546void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005547{
John Kessenich140f3df2015-06-26 16:58:36 -06005548 TIntermNode* root = intermediate.getTreeRoot();
5549
5550 if (root == 0)
5551 return;
5552
5553 glslang::GetThreadPoolAllocator().push();
5554
Lei Zhang17535f72016-05-04 15:55:59 -04005555 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005556 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005557 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005558 it.dumpSpv(spirv);
5559
5560 glslang::GetThreadPoolAllocator().pop();
5561}
5562
5563}; // end namespace glslang