blob: 49bb0a17ca5a3fa3fddd59882aa43bfc05fba602 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
LoopDawg592860c2016-06-09 08:57:35 -06002//Copyright (C) 2014-2016 LunarG, Inc.
John Kessenich6c292d32016-02-15 20:58:50 -07003//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35
36//
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
John Kessenich5e4b1242015-08-06 22:53:06 -060050}
John Kessenich140f3df2015-06-26 16:58:36 -060051
52// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020053#include "../glslang/MachineIndependent/localintermediate.h"
54#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060055#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050056#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060057
John Kessenich140f3df2015-06-26 16:58:36 -060058#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040060#include <list>
61#include <map>
62#include <stack>
63#include <string>
64#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060065
66namespace {
67
John Kessenich55e7d112015-11-15 21:33:39 -070068// For low-order part of the generator's magic number. Bump up
69// when there is a change in the style (e.g., if SSA form changes,
70// or a different instruction sequence to do something gets used).
71const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060072
qining4c912612016-04-01 10:35:16 -040073namespace {
74class SpecConstantOpModeGuard {
75public:
76 SpecConstantOpModeGuard(spv::Builder* builder)
77 : builder_(builder) {
78 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040079 }
80 ~SpecConstantOpModeGuard() {
81 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
82 : builder_->setToNormalCodeGenMode();
83 }
qining40887662016-04-03 22:20:42 -040084 void turnOnSpecConstantOpMode() {
85 builder_->setToSpecConstCodeGenMode();
86 }
qining4c912612016-04-01 10:35:16 -040087
88private:
89 spv::Builder* builder_;
90 bool previous_flag_;
91};
92}
93
John Kessenich140f3df2015-06-26 16:58:36 -060094//
95// The main holder of information for translating glslang to SPIR-V.
96//
97// Derives from the AST walking base class.
98//
99class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
100public:
Lei Zhang17535f72016-05-04 15:55:59 -0400101 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenich140f3df2015-06-26 16:58:36 -0600102 virtual ~TGlslangToSpvTraverser();
103
104 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
105 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
106 void visitConstantUnion(glslang::TIntermConstantUnion*);
107 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
108 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
109 void visitSymbol(glslang::TIntermSymbol* symbol);
110 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
111 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
112 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
113
John Kessenich7ba63412015-12-20 17:37:07 -0700114 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600115
116protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800117 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800118 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100119 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700120 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600121 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
122 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600123 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
124 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
125 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600126 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700127 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600128 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
129 glslang::TLayoutPacking, const glslang::TQualifier&);
130 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
131 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700132 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700133 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800134 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600135 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700136 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700137 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
138 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
139 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 +0100140 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600141
John Kessenich6fccb3c2016-09-19 16:01:41 -0600142 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600143 void makeFunctions(const glslang::TIntermSequence&);
144 void makeGlobalInitializers(const glslang::TIntermSequence&);
145 void visitFunctions(const glslang::TIntermSequence&);
146 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800147 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600148 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
149 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600150 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
151
qining25262b32016-05-06 17:25:16 -0400152 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);
153 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
154 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 +0800155 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 +0800156 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 -0600157 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800158 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 +0800159 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xub7072052016-09-26 15:53:40 +0800160 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600161 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 +0800162 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600163 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
164 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700165 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600166 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700167 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400168 spv::Id createSpvConstant(const glslang::TIntermTyped&);
169 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600170 bool isTrivialLeaf(const glslang::TIntermTyped* node);
171 bool isTrivial(const glslang::TIntermTyped* node);
172 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800173 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600174
175 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600176 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700177 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600178 int sequenceDepth;
179
Lei Zhang17535f72016-05-04 15:55:59 -0400180 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400181
John Kessenich140f3df2015-06-26 16:58:36 -0600182 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
183 spv::Builder builder;
184 bool inMain;
185 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700186 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 -0700187 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600188 const glslang::TIntermediate* glslangIntermediate;
189 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800190 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600191
John Kessenich2f273362015-07-18 22:34:27 -0600192 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600193 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600194 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700195 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600196 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 -0600197 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600198};
199
200//
201// Helper functions for translating glslang representations to SPIR-V enumerants.
202//
203
204// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700205spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600206{
John Kessenich66e2faf2016-03-12 18:34:36 -0700207 switch (source) {
208 case glslang::EShSourceGlsl:
209 switch (profile) {
210 case ENoProfile:
211 case ECoreProfile:
212 case ECompatibilityProfile:
213 return spv::SourceLanguageGLSL;
214 case EEsProfile:
215 return spv::SourceLanguageESSL;
216 default:
217 return spv::SourceLanguageUnknown;
218 }
219 case glslang::EShSourceHlsl:
Dan Baker55d5f2d2016-08-15 16:05:45 -0400220 //Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
221 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600222 default:
223 return spv::SourceLanguageUnknown;
224 }
225}
226
227// Translate glslang language (stage) to SPIR-V execution model.
228spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
229{
230 switch (stage) {
231 case EShLangVertex: return spv::ExecutionModelVertex;
232 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
233 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
234 case EShLangGeometry: return spv::ExecutionModelGeometry;
235 case EShLangFragment: return spv::ExecutionModelFragment;
236 case EShLangCompute: return spv::ExecutionModelGLCompute;
237 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700238 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600239 return spv::ExecutionModelFragment;
240 }
241}
242
243// Translate glslang type to SPIR-V storage class.
244spv::StorageClass TranslateStorageClass(const glslang::TType& type)
245{
246 if (type.getQualifier().isPipeInput())
247 return spv::StorageClassInput;
248 else if (type.getQualifier().isPipeOutput())
249 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700250 else if (type.getBasicType() == glslang::EbtSampler)
251 return spv::StorageClassUniformConstant;
252 else if (type.getBasicType() == glslang::EbtAtomicUint)
253 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600254 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700255 if (type.getQualifier().layoutPushConstant)
256 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600257 if (type.getBasicType() == glslang::EbtBlock)
258 return spv::StorageClassUniform;
259 else
260 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600261 // TODO: how are we distinguishing between default and non-default non-writable uniforms? Do default uniforms even exist?
John Kessenich140f3df2015-06-26 16:58:36 -0600262 } else {
263 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700264 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
265 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600266 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
267 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400268 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700269 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600270 return spv::StorageClassFunction;
271 }
272 }
273}
274
275// Translate glslang sampler type to SPIR-V dimensionality.
276spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
277{
278 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700279 case glslang::Esd1D: return spv::Dim1D;
280 case glslang::Esd2D: return spv::Dim2D;
281 case glslang::Esd3D: return spv::Dim3D;
282 case glslang::EsdCube: return spv::DimCube;
283 case glslang::EsdRect: return spv::DimRect;
284 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700285 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600286 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700287 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600288 return spv::Dim2D;
289 }
290}
291
John Kessenichf6640762016-08-01 19:44:00 -0600292// Translate glslang precision to SPIR-V precision decorations.
293spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600294{
John Kessenichf6640762016-08-01 19:44:00 -0600295 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700296 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600297 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600298 default:
299 return spv::NoPrecision;
300 }
301}
302
John Kessenichf6640762016-08-01 19:44:00 -0600303// Translate glslang type to SPIR-V precision decorations.
304spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
305{
306 return TranslatePrecisionDecoration(type.getQualifier().precision);
307}
308
John Kessenich140f3df2015-06-26 16:58:36 -0600309// Translate glslang type to SPIR-V block decorations.
310spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
311{
312 if (type.getBasicType() == glslang::EbtBlock) {
313 switch (type.getQualifier().storage) {
314 case glslang::EvqUniform: return spv::DecorationBlock;
315 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
316 case glslang::EvqVaryingIn: return spv::DecorationBlock;
317 case glslang::EvqVaryingOut: return spv::DecorationBlock;
318 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700319 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600320 break;
321 }
322 }
323
John Kessenich4016e382016-07-15 11:53:56 -0600324 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600325}
326
Rex Xu1da878f2016-02-21 20:59:01 +0800327// Translate glslang type to SPIR-V memory decorations.
328void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
329{
330 if (qualifier.coherent)
331 memory.push_back(spv::DecorationCoherent);
332 if (qualifier.volatil)
333 memory.push_back(spv::DecorationVolatile);
334 if (qualifier.restrict)
335 memory.push_back(spv::DecorationRestrict);
336 if (qualifier.readonly)
337 memory.push_back(spv::DecorationNonWritable);
338 if (qualifier.writeonly)
339 memory.push_back(spv::DecorationNonReadable);
340}
341
John Kessenich140f3df2015-06-26 16:58:36 -0600342// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700343spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600344{
345 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700346 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600347 case glslang::ElmRowMajor:
348 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700349 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600350 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700351 default:
352 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600353 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600354 }
355 } else {
356 switch (type.getBasicType()) {
357 default:
John Kessenich4016e382016-07-15 11:53:56 -0600358 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600359 break;
360 case glslang::EbtBlock:
361 switch (type.getQualifier().storage) {
362 case glslang::EvqUniform:
363 case glslang::EvqBuffer:
364 switch (type.getQualifier().layoutPacking) {
365 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600366 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
367 default:
John Kessenich4016e382016-07-15 11:53:56 -0600368 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600369 }
370 case glslang::EvqVaryingIn:
371 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700372 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600373 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600374 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700375 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600376 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600377 }
378 }
379 }
380}
381
382// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600383// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700384// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800385spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600386{
Rex Xubbceed72016-05-21 09:40:44 +0800387 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700388 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600389 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800390 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700391 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700392 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600393 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800394#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800395 else if (qualifier.explicitInterp) {
396 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800397 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800398 }
Rex Xu9d93a232016-05-05 12:30:44 +0800399#endif
Rex Xubbceed72016-05-21 09:40:44 +0800400 else
John Kessenich4016e382016-07-15 11:53:56 -0600401 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800402}
403
404// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600405// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800406// should be applied.
407spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
408{
409 if (qualifier.patch)
410 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700411 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600412 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700413 else if (qualifier.sample) {
414 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600415 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700416 } else
John Kessenich4016e382016-07-15 11:53:56 -0600417 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600418}
419
John Kessenich92187592016-02-01 13:45:25 -0700420// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700421spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600422{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700423 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600424 return spv::DecorationInvariant;
425 else
John Kessenich4016e382016-07-15 11:53:56 -0600426 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600427}
428
qining9220dbb2016-05-04 17:34:38 -0400429// If glslang type is noContraction, return SPIR-V NoContraction decoration.
430spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
431{
432 if (qualifier.noContraction)
433 return spv::DecorationNoContraction;
434 else
John Kessenich4016e382016-07-15 11:53:56 -0600435 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400436}
437
David Netoa901ffe2016-06-08 14:11:40 +0100438// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
439// associated capabilities when required. For some built-in variables, a capability
440// is generated only when using the variable in an executable instruction, but not when
441// just declaring a struct member variable with it. This is true for PointSize,
442// ClipDistance, and CullDistance.
443spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600444{
445 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700446 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600447 // Defer adding the capability until the built-in is actually used.
448 if (! memberDeclaration) {
449 switch (glslangIntermediate->getStage()) {
450 case EShLangGeometry:
451 builder.addCapability(spv::CapabilityGeometryPointSize);
452 break;
453 case EShLangTessControl:
454 case EShLangTessEvaluation:
455 builder.addCapability(spv::CapabilityTessellationPointSize);
456 break;
457 default:
458 break;
459 }
John Kessenich92187592016-02-01 13:45:25 -0700460 }
461 return spv::BuiltInPointSize;
462
John Kessenichebb50532016-05-16 19:22:05 -0600463 // These *Distance capabilities logically belong here, but if the member is declared and
464 // then never used, consumers of SPIR-V prefer the capability not be declared.
465 // They are now generated when used, rather than here when declared.
466 // Potentially, the specification should be more clear what the minimum
467 // use needed is to trigger the capability.
468 //
John Kessenich92187592016-02-01 13:45:25 -0700469 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100470 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600471 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700472 return spv::BuiltInClipDistance;
473
474 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100475 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600476 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700477 return spv::BuiltInCullDistance;
478
479 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500480 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700481 return spv::BuiltInViewportIndex;
482
John Kessenich5e801132016-02-15 11:09:46 -0700483 case glslang::EbvSampleId:
484 builder.addCapability(spv::CapabilitySampleRateShading);
485 return spv::BuiltInSampleId;
486
487 case glslang::EbvSamplePosition:
488 builder.addCapability(spv::CapabilitySampleRateShading);
489 return spv::BuiltInSamplePosition;
490
491 case glslang::EbvSampleMask:
492 builder.addCapability(spv::CapabilitySampleRateShading);
493 return spv::BuiltInSampleMask;
494
John Kessenich78a45572016-07-08 14:05:15 -0600495 case glslang::EbvLayer:
496 builder.addCapability(spv::CapabilityGeometry);
497 return spv::BuiltInLayer;
498
John Kessenich140f3df2015-06-26 16:58:36 -0600499 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600500 case glslang::EbvVertexId: return spv::BuiltInVertexId;
501 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700502 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
503 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800504
John Kessenichda581a22015-10-14 14:10:30 -0600505 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800506 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
507 builder.addCapability(spv::CapabilityDrawParameters);
508 return spv::BuiltInBaseVertex;
509
John Kessenichda581a22015-10-14 14:10:30 -0600510 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800511 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
512 builder.addCapability(spv::CapabilityDrawParameters);
513 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200514
John Kessenichda581a22015-10-14 14:10:30 -0600515 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800516 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
517 builder.addCapability(spv::CapabilityDrawParameters);
518 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200519
520 case glslang::EbvPrimitiveId:
521 if (glslangIntermediate->getStage() == EShLangFragment)
522 builder.addCapability(spv::CapabilityGeometry);
523 return spv::BuiltInPrimitiveId;
524
John Kessenich140f3df2015-06-26 16:58:36 -0600525 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600526 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
527 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
528 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
529 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
530 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
531 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
532 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600533 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
534 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
535 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
536 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
537 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
538 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
539 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
540 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800541
Rex Xu574ab042016-04-14 16:53:07 +0800542 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800543 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800544 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
545 return spv::BuiltInSubgroupSize;
546
Rex Xu574ab042016-04-14 16:53:07 +0800547 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800548 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800549 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
550 return spv::BuiltInSubgroupLocalInvocationId;
551
Rex Xu574ab042016-04-14 16:53:07 +0800552 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800553 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
554 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
555 return spv::BuiltInSubgroupEqMaskKHR;
556
Rex Xu574ab042016-04-14 16:53:07 +0800557 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800558 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
559 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
560 return spv::BuiltInSubgroupGeMaskKHR;
561
Rex Xu574ab042016-04-14 16:53:07 +0800562 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800563 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
564 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
565 return spv::BuiltInSubgroupGtMaskKHR;
566
Rex Xu574ab042016-04-14 16:53:07 +0800567 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800568 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
569 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
570 return spv::BuiltInSubgroupLeMaskKHR;
571
Rex Xu574ab042016-04-14 16:53:07 +0800572 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800573 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
574 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
575 return spv::BuiltInSubgroupLtMaskKHR;
576
Rex Xu9d93a232016-05-05 12:30:44 +0800577#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800578 case glslang::EbvBaryCoordNoPersp:
579 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
580 return spv::BuiltInBaryCoordNoPerspAMD;
581
582 case glslang::EbvBaryCoordNoPerspCentroid:
583 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
584 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
585
586 case glslang::EbvBaryCoordNoPerspSample:
587 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
588 return spv::BuiltInBaryCoordNoPerspSampleAMD;
589
590 case glslang::EbvBaryCoordSmooth:
591 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
592 return spv::BuiltInBaryCoordSmoothAMD;
593
594 case glslang::EbvBaryCoordSmoothCentroid:
595 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
596 return spv::BuiltInBaryCoordSmoothCentroidAMD;
597
598 case glslang::EbvBaryCoordSmoothSample:
599 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
600 return spv::BuiltInBaryCoordSmoothSampleAMD;
601
602 case glslang::EbvBaryCoordPullModel:
603 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
604 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800605#endif
John Kessenich4016e382016-07-15 11:53:56 -0600606 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600607 }
608}
609
Rex Xufc618912015-09-09 16:42:49 +0800610// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700611spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800612{
613 assert(type.getBasicType() == glslang::EbtSampler);
614
John Kessenich5d0fa972016-02-15 11:57:00 -0700615 // Check for capabilities
616 switch (type.getQualifier().layoutFormat) {
617 case glslang::ElfRg32f:
618 case glslang::ElfRg16f:
619 case glslang::ElfR11fG11fB10f:
620 case glslang::ElfR16f:
621 case glslang::ElfRgba16:
622 case glslang::ElfRgb10A2:
623 case glslang::ElfRg16:
624 case glslang::ElfRg8:
625 case glslang::ElfR16:
626 case glslang::ElfR8:
627 case glslang::ElfRgba16Snorm:
628 case glslang::ElfRg16Snorm:
629 case glslang::ElfRg8Snorm:
630 case glslang::ElfR16Snorm:
631 case glslang::ElfR8Snorm:
632
633 case glslang::ElfRg32i:
634 case glslang::ElfRg16i:
635 case glslang::ElfRg8i:
636 case glslang::ElfR16i:
637 case glslang::ElfR8i:
638
639 case glslang::ElfRgb10a2ui:
640 case glslang::ElfRg32ui:
641 case glslang::ElfRg16ui:
642 case glslang::ElfRg8ui:
643 case glslang::ElfR16ui:
644 case glslang::ElfR8ui:
645 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
646 break;
647
648 default:
649 break;
650 }
651
652 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800653 switch (type.getQualifier().layoutFormat) {
654 case glslang::ElfNone: return spv::ImageFormatUnknown;
655 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
656 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
657 case glslang::ElfR32f: return spv::ImageFormatR32f;
658 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
659 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
660 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
661 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
662 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
663 case glslang::ElfR16f: return spv::ImageFormatR16f;
664 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
665 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
666 case glslang::ElfRg16: return spv::ImageFormatRg16;
667 case glslang::ElfRg8: return spv::ImageFormatRg8;
668 case glslang::ElfR16: return spv::ImageFormatR16;
669 case glslang::ElfR8: return spv::ImageFormatR8;
670 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
671 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
672 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
673 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
674 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
675 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
676 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
677 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
678 case glslang::ElfR32i: return spv::ImageFormatR32i;
679 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
680 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
681 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
682 case glslang::ElfR16i: return spv::ImageFormatR16i;
683 case glslang::ElfR8i: return spv::ImageFormatR8i;
684 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
685 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
686 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
687 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
688 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
689 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
690 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
691 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
692 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
693 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600694 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800695 }
696}
697
qining25262b32016-05-06 17:25:16 -0400698// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700699// descriptor set.
700bool IsDescriptorResource(const glslang::TType& type)
701{
John Kessenichf7497e22016-03-08 21:36:22 -0700702 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700703 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700704 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700705
706 // non block...
707 // basically samplerXXX/subpass/sampler/texture are all included
708 // if they are the global-scope-class, not the function parameter
709 // (or local, if they ever exist) class.
710 if (type.getBasicType() == glslang::EbtSampler)
711 return type.getQualifier().isUniformOrBuffer();
712
713 // None of the above.
714 return false;
715}
716
John Kesseniche0b6cad2015-12-24 10:30:13 -0700717void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
718{
719 if (child.layoutMatrix == glslang::ElmNone)
720 child.layoutMatrix = parent.layoutMatrix;
721
722 if (parent.invariant)
723 child.invariant = true;
724 if (parent.nopersp)
725 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800726#ifdef AMD_EXTENSIONS
727 if (parent.explicitInterp)
728 child.explicitInterp = true;
729#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700730 if (parent.flat)
731 child.flat = true;
732 if (parent.centroid)
733 child.centroid = true;
734 if (parent.patch)
735 child.patch = true;
736 if (parent.sample)
737 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800738 if (parent.coherent)
739 child.coherent = true;
740 if (parent.volatil)
741 child.volatil = true;
742 if (parent.restrict)
743 child.restrict = true;
744 if (parent.readonly)
745 child.readonly = true;
746 if (parent.writeonly)
747 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700748}
749
John Kessenichf2b7f332016-09-01 17:05:23 -0600750bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700751{
John Kessenich7b9fa252016-01-21 18:56:57 -0700752 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600753 // - struct members might inherit from a struct declaration
754 // (note that non-block structs don't explicitly inherit,
755 // only implicitly, meaning no decoration involved)
756 // - affect decorations on the struct members
757 // (note smooth does not, and expecting something like volatile
758 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700759 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600760 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700761}
762
John Kessenich140f3df2015-06-26 16:58:36 -0600763//
764// Implement the TGlslangToSpvTraverser class.
765//
766
Lei Zhang17535f72016-05-04 15:55:59 -0400767TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600768 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
769 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400770 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600771 inMain(false), mainTerminated(false), linkageOnly(false),
772 glslangIntermediate(glslangIntermediate)
773{
774 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
775
776 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700777 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600778 stdBuiltins = builder.import("GLSL.std.450");
779 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600780 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
781 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600782
783 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600784 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
785 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600786 builder.addSourceExtension(it->c_str());
787
788 // Add the top-level modes for this shader.
789
John Kessenich92187592016-02-01 13:45:25 -0700790 if (glslangIntermediate->getXfbMode()) {
791 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600792 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700793 }
John Kessenich140f3df2015-06-26 16:58:36 -0600794
795 unsigned int mode;
796 switch (glslangIntermediate->getStage()) {
797 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600798 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600799 break;
800
801 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600802 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600803 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
804 break;
805
806 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600807 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600808 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700809 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
810 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
811 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600812 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600813 }
John Kessenich4016e382016-07-15 11:53:56 -0600814 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600815 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
816
John Kesseniche6903322015-10-13 16:29:02 -0600817 switch (glslangIntermediate->getVertexSpacing()) {
818 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
819 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
820 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600821 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600822 }
John Kessenich4016e382016-07-15 11:53:56 -0600823 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600824 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
825
826 switch (glslangIntermediate->getVertexOrder()) {
827 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
828 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600829 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600830 }
John Kessenich4016e382016-07-15 11:53:56 -0600831 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600832 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
833
834 if (glslangIntermediate->getPointMode())
835 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600836 break;
837
838 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600839 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600840 switch (glslangIntermediate->getInputPrimitive()) {
841 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
842 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
843 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700844 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600845 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600846 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600847 }
John Kessenich4016e382016-07-15 11:53:56 -0600848 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600849 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600850
John Kessenich140f3df2015-06-26 16:58:36 -0600851 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
852
853 switch (glslangIntermediate->getOutputPrimitive()) {
854 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
855 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
856 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600857 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600858 }
John Kessenich4016e382016-07-15 11:53:56 -0600859 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600860 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
861 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
862 break;
863
864 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600865 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600866 if (glslangIntermediate->getPixelCenterInteger())
867 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600868
John Kessenich140f3df2015-06-26 16:58:36 -0600869 if (glslangIntermediate->getOriginUpperLeft())
870 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600871 else
872 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600873
874 if (glslangIntermediate->getEarlyFragmentTests())
875 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
876
877 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600878 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
879 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600880 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600881 }
John Kessenich4016e382016-07-15 11:53:56 -0600882 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600883 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
884
885 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
886 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600887 break;
888
889 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600890 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600891 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
892 glslangIntermediate->getLocalSize(1),
893 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600894 break;
895
896 default:
897 break;
898 }
899
900}
901
John Kessenich7ba63412015-12-20 17:37:07 -0700902// Finish everything and dump
903void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
904{
905 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100906 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
907 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700908
qiningda397332016-03-09 19:54:03 -0500909 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700910 builder.dump(out);
911}
912
John Kessenich140f3df2015-06-26 16:58:36 -0600913TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
914{
915 if (! mainTerminated) {
916 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
917 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600918 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600919 }
920}
921
922//
923// Implement the traversal functions.
924//
925// Return true from interior nodes to have the external traversal
926// continue on to children. Return false if children were
927// already processed.
928//
929
930//
qining25262b32016-05-06 17:25:16 -0400931// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600932// - uniform/input reads
933// - output writes
934// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
935// - something simple that degenerates into the last bullet
936//
937void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
938{
qining75d1d802016-04-06 14:42:01 -0400939 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
940 if (symbol->getType().getQualifier().isSpecConstant())
941 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
942
John Kessenich140f3df2015-06-26 16:58:36 -0600943 // getSymbolId() will set up all the IO decorations on the first call.
944 // Formal function parameters were mapped during makeFunctions().
945 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700946
947 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
948 if (builder.isPointer(id)) {
949 spv::StorageClass sc = builder.getStorageClass(id);
950 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
951 iOSet.insert(id);
952 }
953
954 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700955 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600956 // Prepare to generate code for the access
957
958 // L-value chains will be computed left to right. We're on the symbol now,
959 // which is the left-most part of the access chain, so now is "clear" time,
960 // followed by setting the base.
961 builder.clearAccessChain();
962
963 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700964 // except for
John Kessenich4bf71552016-09-02 11:20:21 -0600965 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -0700966 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -0600967 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -0700968 // These are also pure R-values.
969 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -0600970 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -0600971 builder.setAccessChainRValue(id);
972 else
973 builder.setAccessChainLValue(id);
974 }
975}
976
977bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
978{
qining40887662016-04-03 22:20:42 -0400979 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
980 if (node->getType().getQualifier().isSpecConstant())
981 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
982
John Kessenich140f3df2015-06-26 16:58:36 -0600983 // First, handle special cases
984 switch (node->getOp()) {
985 case glslang::EOpAssign:
986 case glslang::EOpAddAssign:
987 case glslang::EOpSubAssign:
988 case glslang::EOpMulAssign:
989 case glslang::EOpVectorTimesMatrixAssign:
990 case glslang::EOpVectorTimesScalarAssign:
991 case glslang::EOpMatrixTimesScalarAssign:
992 case glslang::EOpMatrixTimesMatrixAssign:
993 case glslang::EOpDivAssign:
994 case glslang::EOpModAssign:
995 case glslang::EOpAndAssign:
996 case glslang::EOpInclusiveOrAssign:
997 case glslang::EOpExclusiveOrAssign:
998 case glslang::EOpLeftShiftAssign:
999 case glslang::EOpRightShiftAssign:
1000 // A bin-op assign "a += b" means the same thing as "a = a + b"
1001 // where a is evaluated before b. For a simple assignment, GLSL
1002 // says to evaluate the left before the right. So, always, left
1003 // node then right node.
1004 {
1005 // get the left l-value, save it away
1006 builder.clearAccessChain();
1007 node->getLeft()->traverse(this);
1008 spv::Builder::AccessChain lValue = builder.getAccessChain();
1009
1010 // evaluate the right
1011 builder.clearAccessChain();
1012 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001013 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001014
1015 if (node->getOp() != glslang::EOpAssign) {
1016 // the left is also an r-value
1017 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001018 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001019
1020 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001021 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001022 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001023 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1024 node->getType().getBasicType());
1025
1026 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001027 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001028 }
1029
1030 // store the result
1031 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001032 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001033
1034 // assignments are expressions having an rValue after they are evaluated...
1035 builder.clearAccessChain();
1036 builder.setAccessChainRValue(rValue);
1037 }
1038 return false;
1039 case glslang::EOpIndexDirect:
1040 case glslang::EOpIndexDirectStruct:
1041 {
1042 // Get the left part of the access chain.
1043 node->getLeft()->traverse(this);
1044
1045 // Add the next element in the chain
1046
David Netoa901ffe2016-06-08 14:11:40 +01001047 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001048 if (! node->getLeft()->getType().isArray() &&
1049 node->getLeft()->getType().isVector() &&
1050 node->getOp() == glslang::EOpIndexDirect) {
1051 // This is essentially a hard-coded vector swizzle of size 1,
1052 // so short circuit the access-chain stuff with a swizzle.
1053 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001054 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001055 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001056 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001057 int spvIndex = glslangIndex;
1058 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1059 node->getOp() == glslang::EOpIndexDirectStruct)
1060 {
1061 // This may be, e.g., an anonymous block-member selection, which generally need
1062 // index remapping due to hidden members in anonymous blocks.
1063 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1064 assert(remapper.size() > 0);
1065 spvIndex = remapper[glslangIndex];
1066 }
John Kessenichebb50532016-05-16 19:22:05 -06001067
David Netoa901ffe2016-06-08 14:11:40 +01001068 // normal case for indexing array or structure or block
1069 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1070
1071 // Add capabilities here for accessing PointSize and clip/cull distance.
1072 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001073 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001074 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001075 }
1076 }
1077 return false;
1078 case glslang::EOpIndexIndirect:
1079 {
1080 // Structure or array or vector indirection.
1081 // Will use native SPIR-V access-chain for struct and array indirection;
1082 // matrices are arrays of vectors, so will also work for a matrix.
1083 // Will use the access chain's 'component' for variable index into a vector.
1084
1085 // This adapter is building access chains left to right.
1086 // Set up the access chain to the left.
1087 node->getLeft()->traverse(this);
1088
1089 // save it so that computing the right side doesn't trash it
1090 spv::Builder::AccessChain partial = builder.getAccessChain();
1091
1092 // compute the next index in the chain
1093 builder.clearAccessChain();
1094 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001095 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001096
1097 // restore the saved access chain
1098 builder.setAccessChain(partial);
1099
1100 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001101 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001102 else
John Kessenichfa668da2015-09-13 14:46:30 -06001103 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001104 }
1105 return false;
1106 case glslang::EOpVectorSwizzle:
1107 {
1108 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001109 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001110 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001111 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001112 }
1113 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001114 case glslang::EOpLogicalOr:
1115 case glslang::EOpLogicalAnd:
1116 {
1117
1118 // These may require short circuiting, but can sometimes be done as straight
1119 // binary operations. The right operand must be short circuited if it has
1120 // side effects, and should probably be if it is complex.
1121 if (isTrivial(node->getRight()->getAsTyped()))
1122 break; // handle below as a normal binary operation
1123 // otherwise, we need to do dynamic short circuiting on the right operand
1124 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1125 builder.clearAccessChain();
1126 builder.setAccessChainRValue(result);
1127 }
1128 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001129 default:
1130 break;
1131 }
1132
1133 // Assume generic binary op...
1134
John Kessenich32cfd492016-02-02 12:37:46 -07001135 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001136 builder.clearAccessChain();
1137 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001138 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001139
John Kessenich32cfd492016-02-02 12:37:46 -07001140 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001141 builder.clearAccessChain();
1142 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001143 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001144
John Kessenich32cfd492016-02-02 12:37:46 -07001145 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001146 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001147 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001148 convertGlslangToSpvType(node->getType()), left, right,
1149 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001150
John Kessenich50e57562015-12-21 21:21:11 -07001151 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001152 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001153 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001154 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001155 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001156 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001157 return false;
1158 }
John Kessenich140f3df2015-06-26 16:58:36 -06001159}
1160
1161bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1162{
qining40887662016-04-03 22:20:42 -04001163 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1164 if (node->getType().getQualifier().isSpecConstant())
1165 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1166
John Kessenichfc51d282015-08-19 13:34:18 -06001167 spv::Id result = spv::NoResult;
1168
1169 // try texturing first
1170 result = createImageTextureFunctionCall(node);
1171 if (result != spv::NoResult) {
1172 builder.clearAccessChain();
1173 builder.setAccessChainRValue(result);
1174
1175 return false; // done with this node
1176 }
1177
1178 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001179
1180 if (node->getOp() == glslang::EOpArrayLength) {
1181 // Quite special; won't want to evaluate the operand.
1182
1183 // Normal .length() would have been constant folded by the front-end.
1184 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001185 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001186 assert(node->getOperand()->getType().isRuntimeSizedArray());
1187 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1188 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001189 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1190 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001191
1192 builder.clearAccessChain();
1193 builder.setAccessChainRValue(length);
1194
1195 return false;
1196 }
1197
John Kessenichfc51d282015-08-19 13:34:18 -06001198 // Start by evaluating the operand
1199
John Kessenich8c8505c2016-07-26 12:50:38 -06001200 // Does it need a swizzle inversion? If so, evaluation is inverted;
1201 // operate first on the swizzle base, then apply the swizzle.
1202 spv::Id invertedType = spv::NoType;
1203 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1204 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1205 invertedType = getInvertedSwizzleType(*node->getOperand());
1206
John Kessenich140f3df2015-06-26 16:58:36 -06001207 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001208 if (invertedType != spv::NoType)
1209 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1210 else
1211 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001212
Rex Xufc618912015-09-09 16:42:49 +08001213 spv::Id operand = spv::NoResult;
1214
1215 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1216 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001217 node->getOp() == glslang::EOpAtomicCounter ||
1218 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001219 operand = builder.accessChainGetLValue(); // Special case l-value operands
1220 else
John Kessenich32cfd492016-02-02 12:37:46 -07001221 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001222
John Kessenichf6640762016-08-01 19:44:00 -06001223 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001224 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001225
1226 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001227 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001228 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001229
1230 // if not, then possibly an operation
1231 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001232 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001233
1234 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001235 if (invertedType)
1236 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1237
John Kessenich140f3df2015-06-26 16:58:36 -06001238 builder.clearAccessChain();
1239 builder.setAccessChainRValue(result);
1240
1241 return false; // done with this node
1242 }
1243
1244 // it must be a special case, check...
1245 switch (node->getOp()) {
1246 case glslang::EOpPostIncrement:
1247 case glslang::EOpPostDecrement:
1248 case glslang::EOpPreIncrement:
1249 case glslang::EOpPreDecrement:
1250 {
1251 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001252 spv::Id one = 0;
1253 if (node->getBasicType() == glslang::EbtFloat)
1254 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001255 else if (node->getBasicType() == glslang::EbtDouble)
1256 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001257#ifdef AMD_EXTENSIONS
1258 else if (node->getBasicType() == glslang::EbtFloat16)
1259 one = builder.makeFloat16Constant(1.0F);
1260#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001261 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1262 one = builder.makeInt64Constant(1);
1263 else
1264 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001265 glslang::TOperator op;
1266 if (node->getOp() == glslang::EOpPreIncrement ||
1267 node->getOp() == glslang::EOpPostIncrement)
1268 op = glslang::EOpAdd;
1269 else
1270 op = glslang::EOpSub;
1271
John Kessenichf6640762016-08-01 19:44:00 -06001272 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001273 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001274 convertGlslangToSpvType(node->getType()), operand, one,
1275 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001276 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001277
1278 // The result of operation is always stored, but conditionally the
1279 // consumed result. The consumed result is always an r-value.
1280 builder.accessChainStore(result);
1281 builder.clearAccessChain();
1282 if (node->getOp() == glslang::EOpPreIncrement ||
1283 node->getOp() == glslang::EOpPreDecrement)
1284 builder.setAccessChainRValue(result);
1285 else
1286 builder.setAccessChainRValue(operand);
1287 }
1288
1289 return false;
1290
1291 case glslang::EOpEmitStreamVertex:
1292 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1293 return false;
1294 case glslang::EOpEndStreamPrimitive:
1295 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1296 return false;
1297
1298 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001299 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001300 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001301 }
John Kessenich140f3df2015-06-26 16:58:36 -06001302}
1303
1304bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1305{
qining27e04a02016-04-14 16:40:20 -04001306 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1307 if (node->getType().getQualifier().isSpecConstant())
1308 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1309
John Kessenichfc51d282015-08-19 13:34:18 -06001310 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001311 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1312 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001313
1314 // try texturing
1315 result = createImageTextureFunctionCall(node);
1316 if (result != spv::NoResult) {
1317 builder.clearAccessChain();
1318 builder.setAccessChainRValue(result);
1319
1320 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001321 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001322 // "imageStore" is a special case, which has no result
1323 return false;
1324 }
John Kessenichfc51d282015-08-19 13:34:18 -06001325
John Kessenich140f3df2015-06-26 16:58:36 -06001326 glslang::TOperator binOp = glslang::EOpNull;
1327 bool reduceComparison = true;
1328 bool isMatrix = false;
1329 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001330 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001331
1332 assert(node->getOp());
1333
John Kessenichf6640762016-08-01 19:44:00 -06001334 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001335
1336 switch (node->getOp()) {
1337 case glslang::EOpSequence:
1338 {
1339 if (preVisit)
1340 ++sequenceDepth;
1341 else
1342 --sequenceDepth;
1343
1344 if (sequenceDepth == 1) {
1345 // If this is the parent node of all the functions, we want to see them
1346 // early, so all call points have actual SPIR-V functions to reference.
1347 // In all cases, still let the traverser visit the children for us.
1348 makeFunctions(node->getAsAggregate()->getSequence());
1349
John Kessenich6fccb3c2016-09-19 16:01:41 -06001350 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001351 // anything else gets there, so visit out of order, doing them all now.
1352 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1353
1354 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1355 // so do them manually.
1356 visitFunctions(node->getAsAggregate()->getSequence());
1357
1358 return false;
1359 }
1360
1361 return true;
1362 }
1363 case glslang::EOpLinkerObjects:
1364 {
1365 if (visit == glslang::EvPreVisit)
1366 linkageOnly = true;
1367 else
1368 linkageOnly = false;
1369
1370 return true;
1371 }
1372 case glslang::EOpComma:
1373 {
1374 // processing from left to right naturally leaves the right-most
1375 // lying around in the access chain
1376 glslang::TIntermSequence& glslangOperands = node->getSequence();
1377 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1378 glslangOperands[i]->traverse(this);
1379
1380 return false;
1381 }
1382 case glslang::EOpFunction:
1383 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001384 if (isShaderEntryPoint(node)) {
John Kessenich140f3df2015-06-26 16:58:36 -06001385 inMain = true;
1386 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001387 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001388 } else {
1389 handleFunctionEntry(node);
1390 }
1391 } else {
1392 if (inMain)
1393 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001394 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001395 inMain = false;
1396 }
1397
1398 return true;
1399 case glslang::EOpParameters:
1400 // Parameters will have been consumed by EOpFunction processing, but not
1401 // the body, so we still visited the function node's children, making this
1402 // child redundant.
1403 return false;
1404 case glslang::EOpFunctionCall:
1405 {
1406 if (node->isUserDefined())
1407 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001408 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1409 if (result) {
1410 builder.clearAccessChain();
1411 builder.setAccessChainRValue(result);
1412 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001413 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001414
1415 return false;
1416 }
1417 case glslang::EOpConstructMat2x2:
1418 case glslang::EOpConstructMat2x3:
1419 case glslang::EOpConstructMat2x4:
1420 case glslang::EOpConstructMat3x2:
1421 case glslang::EOpConstructMat3x3:
1422 case glslang::EOpConstructMat3x4:
1423 case glslang::EOpConstructMat4x2:
1424 case glslang::EOpConstructMat4x3:
1425 case glslang::EOpConstructMat4x4:
1426 case glslang::EOpConstructDMat2x2:
1427 case glslang::EOpConstructDMat2x3:
1428 case glslang::EOpConstructDMat2x4:
1429 case glslang::EOpConstructDMat3x2:
1430 case glslang::EOpConstructDMat3x3:
1431 case glslang::EOpConstructDMat3x4:
1432 case glslang::EOpConstructDMat4x2:
1433 case glslang::EOpConstructDMat4x3:
1434 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001435#ifdef AMD_EXTENSIONS
1436 case glslang::EOpConstructF16Mat2x2:
1437 case glslang::EOpConstructF16Mat2x3:
1438 case glslang::EOpConstructF16Mat2x4:
1439 case glslang::EOpConstructF16Mat3x2:
1440 case glslang::EOpConstructF16Mat3x3:
1441 case glslang::EOpConstructF16Mat3x4:
1442 case glslang::EOpConstructF16Mat4x2:
1443 case glslang::EOpConstructF16Mat4x3:
1444 case glslang::EOpConstructF16Mat4x4:
1445#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001446 isMatrix = true;
1447 // fall through
1448 case glslang::EOpConstructFloat:
1449 case glslang::EOpConstructVec2:
1450 case glslang::EOpConstructVec3:
1451 case glslang::EOpConstructVec4:
1452 case glslang::EOpConstructDouble:
1453 case glslang::EOpConstructDVec2:
1454 case glslang::EOpConstructDVec3:
1455 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001456#ifdef AMD_EXTENSIONS
1457 case glslang::EOpConstructFloat16:
1458 case glslang::EOpConstructF16Vec2:
1459 case glslang::EOpConstructF16Vec3:
1460 case glslang::EOpConstructF16Vec4:
1461#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001462 case glslang::EOpConstructBool:
1463 case glslang::EOpConstructBVec2:
1464 case glslang::EOpConstructBVec3:
1465 case glslang::EOpConstructBVec4:
1466 case glslang::EOpConstructInt:
1467 case glslang::EOpConstructIVec2:
1468 case glslang::EOpConstructIVec3:
1469 case glslang::EOpConstructIVec4:
1470 case glslang::EOpConstructUint:
1471 case glslang::EOpConstructUVec2:
1472 case glslang::EOpConstructUVec3:
1473 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001474 case glslang::EOpConstructInt64:
1475 case glslang::EOpConstructI64Vec2:
1476 case glslang::EOpConstructI64Vec3:
1477 case glslang::EOpConstructI64Vec4:
1478 case glslang::EOpConstructUint64:
1479 case glslang::EOpConstructU64Vec2:
1480 case glslang::EOpConstructU64Vec3:
1481 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001482 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001483 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001484 {
1485 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001486 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001487 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001488 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001489 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001490 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001491 std::vector<spv::Id> constituents;
1492 for (int c = 0; c < (int)arguments.size(); ++c)
1493 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001494 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001495 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001496 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001497 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001498 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001499
1500 builder.clearAccessChain();
1501 builder.setAccessChainRValue(constructed);
1502
1503 return false;
1504 }
1505
1506 // These six are component-wise compares with component-wise results.
1507 // Forward on to createBinaryOperation(), requesting a vector result.
1508 case glslang::EOpLessThan:
1509 case glslang::EOpGreaterThan:
1510 case glslang::EOpLessThanEqual:
1511 case glslang::EOpGreaterThanEqual:
1512 case glslang::EOpVectorEqual:
1513 case glslang::EOpVectorNotEqual:
1514 {
1515 // Map the operation to a binary
1516 binOp = node->getOp();
1517 reduceComparison = false;
1518 switch (node->getOp()) {
1519 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1520 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1521 default: binOp = node->getOp(); break;
1522 }
1523
1524 break;
1525 }
1526 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001527 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001528 binOp = glslang::EOpMul;
1529 break;
1530 case glslang::EOpOuterProduct:
1531 // two vectors multiplied to make a matrix
1532 binOp = glslang::EOpOuterProduct;
1533 break;
1534 case glslang::EOpDot:
1535 {
qining25262b32016-05-06 17:25:16 -04001536 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001537 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001538 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001539 binOp = glslang::EOpMul;
1540 break;
1541 }
1542 case glslang::EOpMod:
1543 // when an aggregate, this is the floating-point mod built-in function,
1544 // which can be emitted by the one in createBinaryOperation()
1545 binOp = glslang::EOpMod;
1546 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001547 case glslang::EOpEmitVertex:
1548 case glslang::EOpEndPrimitive:
1549 case glslang::EOpBarrier:
1550 case glslang::EOpMemoryBarrier:
1551 case glslang::EOpMemoryBarrierAtomicCounter:
1552 case glslang::EOpMemoryBarrierBuffer:
1553 case glslang::EOpMemoryBarrierImage:
1554 case glslang::EOpMemoryBarrierShared:
1555 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001556 case glslang::EOpAllMemoryBarrierWithGroupSync:
1557 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1558 case glslang::EOpWorkgroupMemoryBarrier:
1559 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001560 noReturnValue = true;
1561 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1562 break;
1563
John Kessenich426394d2015-07-23 10:22:48 -06001564 case glslang::EOpAtomicAdd:
1565 case glslang::EOpAtomicMin:
1566 case glslang::EOpAtomicMax:
1567 case glslang::EOpAtomicAnd:
1568 case glslang::EOpAtomicOr:
1569 case glslang::EOpAtomicXor:
1570 case glslang::EOpAtomicExchange:
1571 case glslang::EOpAtomicCompSwap:
1572 atomic = true;
1573 break;
1574
John Kessenich140f3df2015-06-26 16:58:36 -06001575 default:
1576 break;
1577 }
1578
1579 //
1580 // See if it maps to a regular operation.
1581 //
John Kessenich140f3df2015-06-26 16:58:36 -06001582 if (binOp != glslang::EOpNull) {
1583 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1584 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1585 assert(left && right);
1586
1587 builder.clearAccessChain();
1588 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001589 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001590
1591 builder.clearAccessChain();
1592 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001593 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001594
qining25262b32016-05-06 17:25:16 -04001595 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001596 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001597 left->getType().getBasicType(), reduceComparison);
1598
1599 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001600 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001601 builder.clearAccessChain();
1602 builder.setAccessChainRValue(result);
1603
1604 return false;
1605 }
1606
John Kessenich426394d2015-07-23 10:22:48 -06001607 //
1608 // Create the list of operands.
1609 //
John Kessenich140f3df2015-06-26 16:58:36 -06001610 glslang::TIntermSequence& glslangOperands = node->getSequence();
1611 std::vector<spv::Id> operands;
1612 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001613 // special case l-value operands; there are just a few
1614 bool lvalue = false;
1615 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001616 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001617 case glslang::EOpModf:
1618 if (arg == 1)
1619 lvalue = true;
1620 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001621 case glslang::EOpInterpolateAtSample:
1622 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001623#ifdef AMD_EXTENSIONS
1624 case glslang::EOpInterpolateAtVertex:
1625#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001626 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001627 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001628
1629 // Does it need a swizzle inversion? If so, evaluation is inverted;
1630 // operate first on the swizzle base, then apply the swizzle.
1631 if (glslangOperands[0]->getAsOperator() &&
1632 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1633 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1634 }
Rex Xu7a26c172015-12-08 17:12:09 +08001635 break;
Rex Xud4782c12015-09-06 16:30:11 +08001636 case glslang::EOpAtomicAdd:
1637 case glslang::EOpAtomicMin:
1638 case glslang::EOpAtomicMax:
1639 case glslang::EOpAtomicAnd:
1640 case glslang::EOpAtomicOr:
1641 case glslang::EOpAtomicXor:
1642 case glslang::EOpAtomicExchange:
1643 case glslang::EOpAtomicCompSwap:
1644 if (arg == 0)
1645 lvalue = true;
1646 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001647 case glslang::EOpAddCarry:
1648 case glslang::EOpSubBorrow:
1649 if (arg == 2)
1650 lvalue = true;
1651 break;
1652 case glslang::EOpUMulExtended:
1653 case glslang::EOpIMulExtended:
1654 if (arg >= 2)
1655 lvalue = true;
1656 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001657 default:
1658 break;
1659 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001660 builder.clearAccessChain();
1661 if (invertedType != spv::NoType && arg == 0)
1662 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1663 else
1664 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001665 if (lvalue)
1666 operands.push_back(builder.accessChainGetLValue());
1667 else
John Kessenich32cfd492016-02-02 12:37:46 -07001668 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001669 }
John Kessenich426394d2015-07-23 10:22:48 -06001670
1671 if (atomic) {
1672 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001673 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001674 } else {
1675 // Pass through to generic operations.
1676 switch (glslangOperands.size()) {
1677 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001678 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001679 break;
1680 case 1:
qining25262b32016-05-06 17:25:16 -04001681 result = createUnaryOperation(
1682 node->getOp(), precision,
1683 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001684 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001685 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001686 break;
1687 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001688 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001689 break;
1690 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001691 if (invertedType)
1692 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001693 }
1694
1695 if (noReturnValue)
1696 return false;
1697
1698 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001699 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001700 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001701 } else {
1702 builder.clearAccessChain();
1703 builder.setAccessChainRValue(result);
1704 return false;
1705 }
1706}
1707
1708bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1709{
1710 // This path handles both if-then-else and ?:
1711 // The if-then-else has a node type of void, while
1712 // ?: has a non-void node type
1713 spv::Id result = 0;
1714 if (node->getBasicType() != glslang::EbtVoid) {
1715 // don't handle this as just on-the-fly temporaries, because there will be two names
1716 // and better to leave SSA to later passes
1717 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1718 }
1719
1720 // emit the condition before doing anything with selection
1721 node->getCondition()->traverse(this);
1722
1723 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001724 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001725
1726 if (node->getTrueBlock()) {
1727 // emit the "then" statement
1728 node->getTrueBlock()->traverse(this);
1729 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001730 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001731 }
1732
1733 if (node->getFalseBlock()) {
1734 ifBuilder.makeBeginElse();
1735 // emit the "else" statement
1736 node->getFalseBlock()->traverse(this);
1737 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001738 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001739 }
1740
1741 ifBuilder.makeEndIf();
1742
1743 if (result) {
1744 // GLSL only has r-values as the result of a :?, but
1745 // if we have an l-value, that can be more efficient if it will
1746 // become the base of a complex r-value expression, because the
1747 // next layer copies r-values into memory to use the access-chain mechanism
1748 builder.clearAccessChain();
1749 builder.setAccessChainLValue(result);
1750 }
1751
1752 return false;
1753}
1754
1755bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1756{
1757 // emit and get the condition before doing anything with switch
1758 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001759 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001760
1761 // browse the children to sort out code segments
1762 int defaultSegment = -1;
1763 std::vector<TIntermNode*> codeSegments;
1764 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1765 std::vector<int> caseValues;
1766 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1767 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1768 TIntermNode* child = *c;
1769 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001770 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001771 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001772 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001773 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1774 } else
1775 codeSegments.push_back(child);
1776 }
1777
qining25262b32016-05-06 17:25:16 -04001778 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001779 // statements between the last case and the end of the switch statement
1780 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1781 (int)codeSegments.size() == defaultSegment)
1782 codeSegments.push_back(nullptr);
1783
1784 // make the switch statement
1785 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001786 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001787
1788 // emit all the code in the segments
1789 breakForLoop.push(false);
1790 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1791 builder.nextSwitchSegment(segmentBlocks, s);
1792 if (codeSegments[s])
1793 codeSegments[s]->traverse(this);
1794 else
1795 builder.addSwitchBreak();
1796 }
1797 breakForLoop.pop();
1798
1799 builder.endSwitch(segmentBlocks);
1800
1801 return false;
1802}
1803
1804void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1805{
1806 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001807 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001808
1809 builder.clearAccessChain();
1810 builder.setAccessChainRValue(constant);
1811}
1812
1813bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1814{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001815 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001816 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001817 // Spec requires back edges to target header blocks, and every header block
1818 // must dominate its merge block. Make a header block first to ensure these
1819 // conditions are met. By definition, it will contain OpLoopMerge, followed
1820 // by a block-ending branch. But we don't want to put any other body/test
1821 // instructions in it, since the body/test may have arbitrary instructions,
1822 // including merges of its own.
1823 builder.setBuildPoint(&blocks.head);
1824 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001825 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001826 spv::Block& test = builder.makeNewBlock();
1827 builder.createBranch(&test);
1828
1829 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001830 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001831 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001832 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001833 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1834
1835 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001836 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001837 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001838 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001839 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001840 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001841
1842 builder.setBuildPoint(&blocks.continue_target);
1843 if (node->getTerminal())
1844 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001845 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001846 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001847 builder.createBranch(&blocks.body);
1848
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001849 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001850 builder.setBuildPoint(&blocks.body);
1851 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001852 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001853 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001854 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001855
1856 builder.setBuildPoint(&blocks.continue_target);
1857 if (node->getTerminal())
1858 node->getTerminal()->traverse(this);
1859 if (node->getTest()) {
1860 node->getTest()->traverse(this);
1861 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001862 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001863 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001864 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001865 // TODO: unless there was a break/return/discard instruction
1866 // somewhere in the body, this is an infinite loop, so we should
1867 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001868 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001869 }
John Kessenich140f3df2015-06-26 16:58:36 -06001870 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001871 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001872 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001873 return false;
1874}
1875
1876bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1877{
1878 if (node->getExpression())
1879 node->getExpression()->traverse(this);
1880
1881 switch (node->getFlowOp()) {
1882 case glslang::EOpKill:
1883 builder.makeDiscard();
1884 break;
1885 case glslang::EOpBreak:
1886 if (breakForLoop.top())
1887 builder.createLoopExit();
1888 else
1889 builder.addSwitchBreak();
1890 break;
1891 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001892 builder.createLoopContinue();
1893 break;
1894 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06001895 if (node->getExpression()) {
1896 const glslang::TType& glslangReturnType = node->getExpression()->getType();
1897 spv::Id returnId = accessChainLoad(glslangReturnType);
1898 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
1899 builder.clearAccessChain();
1900 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
1901 builder.setAccessChainLValue(copyId);
1902 multiTypeStore(glslangReturnType, returnId);
1903 returnId = builder.createLoad(copyId);
1904 }
1905 builder.makeReturn(false, returnId);
1906 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06001907 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001908
1909 builder.clearAccessChain();
1910 break;
1911
1912 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001913 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001914 break;
1915 }
1916
1917 return false;
1918}
1919
1920spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1921{
qining25262b32016-05-06 17:25:16 -04001922 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001923 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001924 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001925 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001926 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001927 }
1928
1929 // Now, handle actual variables
1930 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1931 spv::Id spvType = convertGlslangToSpvType(node->getType());
1932
1933 const char* name = node->getName().c_str();
1934 if (glslang::IsAnonymous(name))
1935 name = "";
1936
1937 return builder.createVariable(storageClass, spvType, name);
1938}
1939
1940// Return type Id of the sampled type.
1941spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1942{
1943 switch (sampler.type) {
1944 case glslang::EbtFloat: return builder.makeFloatType(32);
1945 case glslang::EbtInt: return builder.makeIntType(32);
1946 case glslang::EbtUint: return builder.makeUintType(32);
1947 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001948 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001949 return builder.makeFloatType(32);
1950 }
1951}
1952
John Kessenich8c8505c2016-07-26 12:50:38 -06001953// If node is a swizzle operation, return the type that should be used if
1954// the swizzle base is first consumed by another operation, before the swizzle
1955// is applied.
1956spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1957{
1958 if (node.getAsOperator() &&
1959 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1960 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1961 else
1962 return spv::NoType;
1963}
1964
1965// When inverting a swizzle with a parent op, this function
1966// will apply the swizzle operation to a completed parent operation.
1967spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1968{
1969 std::vector<unsigned> swizzle;
1970 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1971 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1972}
1973
John Kessenich8c8505c2016-07-26 12:50:38 -06001974// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1975void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1976{
1977 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1978 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1979 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1980}
1981
John Kessenich3ac051e2015-12-20 11:29:16 -07001982// Convert from a glslang type to an SPV type, by calling into a
1983// recursive version of this function. This establishes the inherited
1984// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001985spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1986{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001987 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001988}
1989
1990// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001991// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001992// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001993spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001994{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001995 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001996
1997 switch (type.getBasicType()) {
1998 case glslang::EbtVoid:
1999 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002000 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002001 break;
2002 case glslang::EbtFloat:
2003 spvType = builder.makeFloatType(32);
2004 break;
2005 case glslang::EbtDouble:
2006 spvType = builder.makeFloatType(64);
2007 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002008#ifdef AMD_EXTENSIONS
2009 case glslang::EbtFloat16:
2010 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
2011 builder.addCapability(spv::CapabilityFloat16);
2012 spvType = builder.makeFloatType(16);
2013 break;
2014#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002015 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002016 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2017 // a 32-bit int where non-0 means true.
2018 if (explicitLayout != glslang::ElpNone)
2019 spvType = builder.makeUintType(32);
2020 else
2021 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002022 break;
2023 case glslang::EbtInt:
2024 spvType = builder.makeIntType(32);
2025 break;
2026 case glslang::EbtUint:
2027 spvType = builder.makeUintType(32);
2028 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002029 case glslang::EbtInt64:
2030 builder.addCapability(spv::CapabilityInt64);
2031 spvType = builder.makeIntType(64);
2032 break;
2033 case glslang::EbtUint64:
2034 builder.addCapability(spv::CapabilityInt64);
2035 spvType = builder.makeUintType(64);
2036 break;
John Kessenich426394d2015-07-23 10:22:48 -06002037 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002038 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002039 spvType = builder.makeUintType(32);
2040 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002041 case glslang::EbtSampler:
2042 {
2043 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002044 if (sampler.sampler) {
2045 // pure sampler
2046 spvType = builder.makeSamplerType();
2047 } else {
2048 // an image is present, make its type
2049 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2050 sampler.image ? 2 : 1, TranslateImageFormat(type));
2051 if (sampler.combined) {
2052 // already has both image and sampler, make the combined type
2053 spvType = builder.makeSampledImageType(spvType);
2054 }
John Kessenich55e7d112015-11-15 21:33:39 -07002055 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002056 }
John Kessenich140f3df2015-06-26 16:58:36 -06002057 break;
2058 case glslang::EbtStruct:
2059 case glslang::EbtBlock:
2060 {
2061 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002062 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002063
2064 // Try to share structs for different layouts, but not yet for other
2065 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002066 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002067 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002068 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002069 break;
2070
2071 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002072 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002073 memberRemapper[glslangMembers].resize(glslangMembers->size());
2074 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002075 }
2076 break;
2077 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002078 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002079 break;
2080 }
2081
2082 if (type.isMatrix())
2083 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2084 else {
2085 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2086 if (type.getVectorSize() > 1)
2087 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2088 }
2089
2090 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002091 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2092
John Kessenichc9a80832015-09-12 12:17:44 -06002093 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002094 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002095 // We need to decorate array strides for types needing explicit layout, except blocks.
2096 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002097 // Use a dummy glslang type for querying internal strides of
2098 // arrays of arrays, but using just a one-dimensional array.
2099 glslang::TType simpleArrayType(type, 0); // deference type of the array
2100 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2101 simpleArrayType.getArraySizes().dereference();
2102
2103 // Will compute the higher-order strides here, rather than making a whole
2104 // pile of types and doing repetitive recursion on their contents.
2105 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2106 }
John Kessenichf8842e52016-01-04 19:22:56 -07002107
2108 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002109 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002110 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002111 if (stride > 0)
2112 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002113 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002114 }
2115 } else {
2116 // single-dimensional array, and don't yet have stride
2117
John Kessenichf8842e52016-01-04 19:22:56 -07002118 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002119 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2120 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002121 }
John Kessenich31ed4832015-09-09 17:51:38 -06002122
John Kessenichc9a80832015-09-12 12:17:44 -06002123 // Do the outer dimension, which might not be known for a runtime-sized array
2124 if (type.isRuntimeSizedArray()) {
2125 spvType = builder.makeRuntimeArray(spvType);
2126 } else {
2127 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002128 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002129 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002130 if (stride > 0)
2131 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002132 }
2133
2134 return spvType;
2135}
2136
John Kessenich6090df02016-06-30 21:18:02 -06002137
2138// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2139// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2140// Mutually recursive with convertGlslangToSpvType().
2141spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2142 const glslang::TTypeList* glslangMembers,
2143 glslang::TLayoutPacking explicitLayout,
2144 const glslang::TQualifier& qualifier)
2145{
2146 // Create a vector of struct types for SPIR-V to consume
2147 std::vector<spv::Id> spvMembers;
2148 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2149 int locationOffset = 0; // for use across struct members, when they are called recursively
2150 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2151 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2152 if (glslangMember.hiddenMember()) {
2153 ++memberDelta;
2154 if (type.getBasicType() == glslang::EbtBlock)
2155 memberRemapper[glslangMembers][i] = -1;
2156 } else {
2157 if (type.getBasicType() == glslang::EbtBlock)
2158 memberRemapper[glslangMembers][i] = i - memberDelta;
2159 // modify just this child's view of the qualifier
2160 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2161 InheritQualifiers(memberQualifier, qualifier);
2162
2163 // manually inherit location; it's more complex
2164 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2165 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2166 if (qualifier.hasLocation())
2167 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2168
2169 // recurse
2170 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2171 }
2172 }
2173
2174 // Make the SPIR-V type
2175 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002176 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002177 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2178
2179 // Decorate it
2180 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2181
2182 return spvType;
2183}
2184
2185void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2186 const glslang::TTypeList* glslangMembers,
2187 glslang::TLayoutPacking explicitLayout,
2188 const glslang::TQualifier& qualifier,
2189 spv::Id spvType)
2190{
2191 // Name and decorate the non-hidden members
2192 int offset = -1;
2193 int locationOffset = 0; // for use within the members of this struct
2194 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2195 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2196 int member = i;
2197 if (type.getBasicType() == glslang::EbtBlock)
2198 member = memberRemapper[glslangMembers][i];
2199
2200 // modify just this child's view of the qualifier
2201 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2202 InheritQualifiers(memberQualifier, qualifier);
2203
2204 // using -1 above to indicate a hidden member
2205 if (member >= 0) {
2206 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2207 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2208 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2209 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2210 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2211 if (type.getBasicType() == glslang::EbtBlock) {
2212 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2213 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2214 }
2215 }
2216 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2217
2218 if (qualifier.storage == glslang::EvqBuffer) {
2219 std::vector<spv::Decoration> memory;
2220 TranslateMemoryDecoration(memberQualifier, memory);
2221 for (unsigned int i = 0; i < memory.size(); ++i)
2222 addMemberDecoration(spvType, member, memory[i]);
2223 }
2224
John Kessenich2f47bc92016-06-30 21:47:35 -06002225 // Compute location decoration; tricky based on whether inheritance is at play and
2226 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002227 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2228 // probably move to the linker stage of the front end proper, and just have the
2229 // answer sitting already distributed throughout the individual member locations.
2230 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002231 // Ignore member locations if the container is an array, as that's
2232 // ill-specified and decisions have been made to not allow this anyway.
2233 // The object itself must have a location, and that comes out from decorating the object,
2234 // not the type (this code decorates types).
2235 if (! type.isArray()) {
2236 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2237 // struct members should not have explicit locations
2238 assert(type.getBasicType() != glslang::EbtStruct);
2239 location = memberQualifier.layoutLocation;
2240 } else if (type.getBasicType() != glslang::EbtBlock) {
2241 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2242 // The members, and their nested types, must not themselves have Location decorations.
2243 } else if (qualifier.hasLocation()) // inheritance
2244 location = qualifier.layoutLocation + locationOffset;
2245 }
John Kessenich6090df02016-06-30 21:18:02 -06002246 if (location >= 0)
2247 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2248
John Kessenich2f47bc92016-06-30 21:47:35 -06002249 if (qualifier.hasLocation()) // track for upcoming inheritance
2250 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2251
John Kessenich6090df02016-06-30 21:18:02 -06002252 // component, XFB, others
2253 if (glslangMember.getQualifier().hasComponent())
2254 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2255 if (glslangMember.getQualifier().hasXfbOffset())
2256 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2257 else if (explicitLayout != glslang::ElpNone) {
2258 // figure out what to do with offset, which is accumulating
2259 int nextOffset;
2260 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2261 if (offset >= 0)
2262 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2263 offset = nextOffset;
2264 }
2265
2266 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2267 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2268
2269 // built-in variable decorations
2270 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002271 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002272 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2273 }
2274 }
2275
2276 // Decorate the structure
2277 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2278 addDecoration(spvType, TranslateBlockDecoration(type));
2279 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2280 builder.addCapability(spv::CapabilityGeometryStreams);
2281 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2282 }
2283 if (glslangIntermediate->getXfbMode()) {
2284 builder.addCapability(spv::CapabilityTransformFeedback);
2285 if (type.getQualifier().hasXfbStride())
2286 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2287 if (type.getQualifier().hasXfbBuffer())
2288 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2289 }
2290}
2291
John Kessenich6c292d32016-02-15 20:58:50 -07002292// Turn the expression forming the array size into an id.
2293// This is not quite trivial, because of specialization constants.
2294// Sometimes, a raw constant is turned into an Id, and sometimes
2295// a specialization constant expression is.
2296spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2297{
2298 // First, see if this is sized with a node, meaning a specialization constant:
2299 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2300 if (specNode != nullptr) {
2301 builder.clearAccessChain();
2302 specNode->traverse(this);
2303 return accessChainLoad(specNode->getAsTyped()->getType());
2304 }
qining25262b32016-05-06 17:25:16 -04002305
John Kessenich6c292d32016-02-15 20:58:50 -07002306 // Otherwise, need a compile-time (front end) size, get it:
2307 int size = arraySizes.getDimSize(dim);
2308 assert(size > 0);
2309 return builder.makeUintConstant(size);
2310}
2311
John Kessenich103bef92016-02-08 21:38:15 -07002312// Wrap the builder's accessChainLoad to:
2313// - localize handling of RelaxedPrecision
2314// - use the SPIR-V inferred type instead of another conversion of the glslang type
2315// (avoids unnecessary work and possible type punning for structures)
2316// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002317spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2318{
John Kessenich103bef92016-02-08 21:38:15 -07002319 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2320 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2321
2322 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002323 if (type.getBasicType() == glslang::EbtBool) {
2324 if (builder.isScalarType(nominalTypeId)) {
2325 // Conversion for bool
2326 spv::Id boolType = builder.makeBoolType();
2327 if (nominalTypeId != boolType)
2328 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2329 } else if (builder.isVectorType(nominalTypeId)) {
2330 // Conversion for bvec
2331 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2332 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2333 if (nominalTypeId != bvecType)
2334 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2335 }
2336 }
John Kessenich103bef92016-02-08 21:38:15 -07002337
2338 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002339}
2340
Rex Xu27253232016-02-23 17:51:09 +08002341// Wrap the builder's accessChainStore to:
2342// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002343//
2344// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002345void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2346{
2347 // Need to convert to abstract types when necessary
2348 if (type.getBasicType() == glslang::EbtBool) {
2349 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2350
2351 if (builder.isScalarType(nominalTypeId)) {
2352 // Conversion for bool
2353 spv::Id boolType = builder.makeBoolType();
2354 if (nominalTypeId != boolType) {
2355 spv::Id zero = builder.makeUintConstant(0);
2356 spv::Id one = builder.makeUintConstant(1);
2357 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2358 }
2359 } else if (builder.isVectorType(nominalTypeId)) {
2360 // Conversion for bvec
2361 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2362 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2363 if (nominalTypeId != bvecType) {
2364 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2365 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2366 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2367 }
2368 }
2369 }
2370
2371 builder.accessChainStore(rvalue);
2372}
2373
John Kessenich4bf71552016-09-02 11:20:21 -06002374// For storing when types match at the glslang level, but not might match at the
2375// SPIR-V level.
2376//
2377// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002378// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002379// as in a member-decorated way.
2380//
2381// NOTE: This function can handle any store request; if it's not special it
2382// simplifies to a simple OpStore.
2383//
2384// Implicitly uses the existing builder.accessChain as the storage target.
2385void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2386{
John Kessenichb3e24e42016-09-11 12:33:43 -06002387 // we only do the complex path here if it's an aggregate
2388 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002389 accessChainStore(type, rValue);
2390 return;
2391 }
2392
John Kessenichb3e24e42016-09-11 12:33:43 -06002393 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002394 spv::Id rType = builder.getTypeId(rValue);
2395 spv::Id lValue = builder.accessChainGetLValue();
2396 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2397 if (lType == rType) {
2398 accessChainStore(type, rValue);
2399 return;
2400 }
2401
John Kessenichb3e24e42016-09-11 12:33:43 -06002402 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002403 // where the two types were the same type in GLSL. This requires member
2404 // by member copy, recursively.
2405
John Kessenichb3e24e42016-09-11 12:33:43 -06002406 // If an array, copy element by element.
2407 if (type.isArray()) {
2408 glslang::TType glslangElementType(type, 0);
2409 spv::Id elementRType = builder.getContainedTypeId(rType);
2410 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2411 // get the source member
2412 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002413
John Kessenichb3e24e42016-09-11 12:33:43 -06002414 // set up the target storage
2415 builder.clearAccessChain();
2416 builder.setAccessChainLValue(lValue);
2417 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002418
John Kessenichb3e24e42016-09-11 12:33:43 -06002419 // store the member
2420 multiTypeStore(glslangElementType, elementRValue);
2421 }
2422 } else {
2423 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002424
John Kessenichb3e24e42016-09-11 12:33:43 -06002425 // loop over structure members
2426 const glslang::TTypeList& members = *type.getStruct();
2427 for (int m = 0; m < (int)members.size(); ++m) {
2428 const glslang::TType& glslangMemberType = *members[m].type;
2429
2430 // get the source member
2431 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2432 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2433
2434 // set up the target storage
2435 builder.clearAccessChain();
2436 builder.setAccessChainLValue(lValue);
2437 builder.accessChainPush(builder.makeIntConstant(m));
2438
2439 // store the member
2440 multiTypeStore(glslangMemberType, memberRValue);
2441 }
John Kessenich4bf71552016-09-02 11:20:21 -06002442 }
2443}
2444
John Kessenichf85e8062015-12-19 13:57:10 -07002445// Decide whether or not this type should be
2446// decorated with offsets and strides, and if so
2447// whether std140 or std430 rules should be applied.
2448glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002449{
John Kessenichf85e8062015-12-19 13:57:10 -07002450 // has to be a block
2451 if (type.getBasicType() != glslang::EbtBlock)
2452 return glslang::ElpNone;
2453
2454 // has to be a uniform or buffer block
2455 if (type.getQualifier().storage != glslang::EvqUniform &&
2456 type.getQualifier().storage != glslang::EvqBuffer)
2457 return glslang::ElpNone;
2458
2459 // return the layout to use
2460 switch (type.getQualifier().layoutPacking) {
2461 case glslang::ElpStd140:
2462 case glslang::ElpStd430:
2463 return type.getQualifier().layoutPacking;
2464 default:
2465 return glslang::ElpNone;
2466 }
John Kessenich31ed4832015-09-09 17:51:38 -06002467}
2468
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002469// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002470int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002471{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002472 int size;
John Kessenich49987892015-12-29 17:11:44 -07002473 int stride;
2474 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002475
2476 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002477}
2478
John Kessenich49987892015-12-29 17:11:44 -07002479// 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 -07002480// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002481int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002482{
John Kessenich49987892015-12-29 17:11:44 -07002483 glslang::TType elementType;
2484 elementType.shallowCopy(matrixType);
2485 elementType.clearArraySizes();
2486
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002487 int size;
John Kessenich49987892015-12-29 17:11:44 -07002488 int stride;
2489 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2490
2491 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002492}
2493
John Kessenich5e4b1242015-08-06 22:53:06 -06002494// Given a member type of a struct, realign the current offset for it, and compute
2495// the next (not yet aligned) offset for the next member, which will get aligned
2496// on the next call.
2497// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2498// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2499// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002500void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002501 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002502{
2503 // this will get a positive value when deemed necessary
2504 nextOffset = -1;
2505
John Kessenich5e4b1242015-08-06 22:53:06 -06002506 // override anything in currentOffset with user-set offset
2507 if (memberType.getQualifier().hasOffset())
2508 currentOffset = memberType.getQualifier().layoutOffset;
2509
2510 // It could be that current linker usage in glslang updated all the layoutOffset,
2511 // in which case the following code does not matter. But, that's not quite right
2512 // once cross-compilation unit GLSL validation is done, as the original user
2513 // settings are needed in layoutOffset, and then the following will come into play.
2514
John Kessenichf85e8062015-12-19 13:57:10 -07002515 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002516 if (! memberType.getQualifier().hasOffset())
2517 currentOffset = -1;
2518
2519 return;
2520 }
2521
John Kessenichf85e8062015-12-19 13:57:10 -07002522 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002523 if (currentOffset < 0)
2524 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002525
John Kessenich5e4b1242015-08-06 22:53:06 -06002526 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2527 // but possibly not yet correctly aligned.
2528
2529 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002530 int dummyStride;
2531 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002532 glslang::RoundToPow2(currentOffset, memberAlignment);
2533 nextOffset = currentOffset + memberSize;
2534}
2535
David Netoa901ffe2016-06-08 14:11:40 +01002536void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002537{
David Netoa901ffe2016-06-08 14:11:40 +01002538 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2539 switch (glslangBuiltIn)
2540 {
2541 case glslang::EbvClipDistance:
2542 case glslang::EbvCullDistance:
2543 case glslang::EbvPointSize:
2544 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2545 // Alternately, we could just call this for any glslang built-in, since the
2546 // capability already guards against duplicates.
2547 TranslateBuiltInDecoration(glslangBuiltIn, false);
2548 break;
2549 default:
2550 // Capabilities were already generated when the struct was declared.
2551 break;
2552 }
John Kessenichebb50532016-05-16 19:22:05 -06002553}
2554
John Kessenich6fccb3c2016-09-19 16:01:41 -06002555bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002556{
John Kessenicheee9d532016-09-19 18:09:30 -06002557 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002558}
2559
2560// Make all the functions, skeletally, without actually visiting their bodies.
2561void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2562{
2563 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2564 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002565 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002566 continue;
2567
2568 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002569 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002570 //
qining25262b32016-05-06 17:25:16 -04002571 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002572 // function. What it is an address of varies:
2573 //
John Kessenich4bf71552016-09-02 11:20:21 -06002574 // - "in" parameters not marked as "const" can be written to without modifying the calling
2575 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002576 //
2577 // - "const in" parameters can just be the r-value, as no writes need occur.
2578 //
John Kessenich4bf71552016-09-02 11:20:21 -06002579 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2580 // 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 -06002581
2582 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002583 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002584 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2585
2586 for (int p = 0; p < (int)parameters.size(); ++p) {
2587 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2588 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002589 if (paramType.isOpaque())
2590 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2591 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002592 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2593 else
John Kessenich4bf71552016-09-02 11:20:21 -06002594 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002595 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002596 paramTypes.push_back(typeId);
2597 }
2598
2599 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002600 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2601 convertGlslangToSpvType(glslFunction->getType()),
2602 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002603
2604 // Track function to emit/call later
2605 functionMap[glslFunction->getName().c_str()] = function;
2606
2607 // Set the parameter id's
2608 for (int p = 0; p < (int)parameters.size(); ++p) {
2609 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2610 // give a name too
2611 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2612 }
2613 }
2614}
2615
2616// Process all the initializers, while skipping the functions and link objects
2617void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2618{
2619 builder.setBuildPoint(shaderEntry->getLastBlock());
2620 for (int i = 0; i < (int)initializers.size(); ++i) {
2621 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2622 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2623
2624 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002625 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002626 initializer->traverse(this);
2627 }
2628 }
2629}
2630
2631// Process all the functions, while skipping initializers.
2632void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2633{
2634 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2635 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2636 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2637 node->traverse(this);
2638 }
2639}
2640
2641void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2642{
qining25262b32016-05-06 17:25:16 -04002643 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002644 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002645 currentFunction = functionMap[node->getName().c_str()];
2646 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002647 builder.setBuildPoint(functionBlock);
2648}
2649
Rex Xu04db3f52015-09-16 11:44:02 +08002650void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002651{
Rex Xufc618912015-09-09 16:42:49 +08002652 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002653
2654 glslang::TSampler sampler = {};
2655 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002656 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002657 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2658 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2659 }
2660
John Kessenich140f3df2015-06-26 16:58:36 -06002661 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2662 builder.clearAccessChain();
2663 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002664
2665 // Special case l-value operands
2666 bool lvalue = false;
2667 switch (node.getOp()) {
2668 case glslang::EOpImageAtomicAdd:
2669 case glslang::EOpImageAtomicMin:
2670 case glslang::EOpImageAtomicMax:
2671 case glslang::EOpImageAtomicAnd:
2672 case glslang::EOpImageAtomicOr:
2673 case glslang::EOpImageAtomicXor:
2674 case glslang::EOpImageAtomicExchange:
2675 case glslang::EOpImageAtomicCompSwap:
2676 if (i == 0)
2677 lvalue = true;
2678 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002679 case glslang::EOpSparseImageLoad:
2680 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2681 lvalue = true;
2682 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002683 case glslang::EOpSparseTexture:
2684 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2685 lvalue = true;
2686 break;
2687 case glslang::EOpSparseTextureClamp:
2688 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2689 lvalue = true;
2690 break;
2691 case glslang::EOpSparseTextureLod:
2692 case glslang::EOpSparseTextureOffset:
2693 if (i == 3)
2694 lvalue = true;
2695 break;
2696 case glslang::EOpSparseTextureFetch:
2697 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2698 lvalue = true;
2699 break;
2700 case glslang::EOpSparseTextureFetchOffset:
2701 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2702 lvalue = true;
2703 break;
2704 case glslang::EOpSparseTextureLodOffset:
2705 case glslang::EOpSparseTextureGrad:
2706 case glslang::EOpSparseTextureOffsetClamp:
2707 if (i == 4)
2708 lvalue = true;
2709 break;
2710 case glslang::EOpSparseTextureGradOffset:
2711 case glslang::EOpSparseTextureGradClamp:
2712 if (i == 5)
2713 lvalue = true;
2714 break;
2715 case glslang::EOpSparseTextureGradOffsetClamp:
2716 if (i == 6)
2717 lvalue = true;
2718 break;
2719 case glslang::EOpSparseTextureGather:
2720 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2721 lvalue = true;
2722 break;
2723 case glslang::EOpSparseTextureGatherOffset:
2724 case glslang::EOpSparseTextureGatherOffsets:
2725 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2726 lvalue = true;
2727 break;
Rex Xufc618912015-09-09 16:42:49 +08002728 default:
2729 break;
2730 }
2731
Rex Xu6b86d492015-09-16 17:48:22 +08002732 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002733 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002734 else
John Kessenich32cfd492016-02-02 12:37:46 -07002735 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002736 }
2737}
2738
John Kessenichfc51d282015-08-19 13:34:18 -06002739void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002740{
John Kessenichfc51d282015-08-19 13:34:18 -06002741 builder.clearAccessChain();
2742 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002743 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002744}
John Kessenich140f3df2015-06-26 16:58:36 -06002745
John Kessenichfc51d282015-08-19 13:34:18 -06002746spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2747{
Rex Xufc618912015-09-09 16:42:49 +08002748 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002749 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002750 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002751 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002752
John Kessenichfc51d282015-08-19 13:34:18 -06002753 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002754 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2755 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2756 std::vector<spv::Id> arguments;
2757 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002758 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002759 else
2760 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002761 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002762
2763 spv::Builder::TextureParameters params = { };
2764 params.sampler = arguments[0];
2765
Rex Xu04db3f52015-09-16 11:44:02 +08002766 glslang::TCrackedTextureOp cracked;
2767 node->crackTexture(sampler, cracked);
2768
John Kessenichfc51d282015-08-19 13:34:18 -06002769 // Check for queries
2770 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002771 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2772 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002773 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002774
John Kessenichfc51d282015-08-19 13:34:18 -06002775 switch (node->getOp()) {
2776 case glslang::EOpImageQuerySize:
2777 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002778 if (arguments.size() > 1) {
2779 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002780 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002781 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002782 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002783 case glslang::EOpImageQuerySamples:
2784 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002785 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002786 case glslang::EOpTextureQueryLod:
2787 params.coords = arguments[1];
2788 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2789 case glslang::EOpTextureQueryLevels:
2790 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002791 case glslang::EOpSparseTexelsResident:
2792 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002793 default:
2794 assert(0);
2795 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002796 }
John Kessenich140f3df2015-06-26 16:58:36 -06002797 }
2798
Rex Xufc618912015-09-09 16:42:49 +08002799 // Check for image functions other than queries
2800 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002801 std::vector<spv::Id> operands;
2802 auto opIt = arguments.begin();
2803 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002804
2805 // Handle subpass operations
2806 // TODO: GLSL should change to have the "MS" only on the type rather than the
2807 // built-in function.
2808 if (cracked.subpass) {
2809 // add on the (0,0) coordinate
2810 spv::Id zero = builder.makeIntConstant(0);
2811 std::vector<spv::Id> comps;
2812 comps.push_back(zero);
2813 comps.push_back(zero);
2814 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2815 if (sampler.ms) {
2816 operands.push_back(spv::ImageOperandsSampleMask);
2817 operands.push_back(*(opIt++));
2818 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002819 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002820 }
2821
John Kessenich56bab042015-09-16 10:54:31 -06002822 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002823 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002824 if (sampler.ms) {
2825 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002826 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002827 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002828 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2829 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002830 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002831 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002832 if (sampler.ms) {
2833 operands.push_back(*(opIt + 1));
2834 operands.push_back(spv::ImageOperandsSampleMask);
2835 operands.push_back(*opIt);
2836 } else
2837 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002838 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002839 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2840 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002841 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002842 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2843 builder.addCapability(spv::CapabilitySparseResidency);
2844 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2845 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2846
2847 if (sampler.ms) {
2848 operands.push_back(spv::ImageOperandsSampleMask);
2849 operands.push_back(*opIt++);
2850 }
2851
2852 // Create the return type that was a special structure
2853 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002854 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002855 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2856 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2857
2858 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2859
2860 // Decode the return type
2861 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2862 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002863 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002864 // Process image atomic operations
2865
2866 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2867 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002868 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002869
John Kessenich8c8505c2016-07-26 12:50:38 -06002870 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002871 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002872
2873 std::vector<spv::Id> operands;
2874 operands.push_back(pointer);
2875 for (; opIt != arguments.end(); ++opIt)
2876 operands.push_back(*opIt);
2877
John Kessenich8c8505c2016-07-26 12:50:38 -06002878 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002879 }
2880 }
2881
2882 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002883 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002884 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2885
John Kessenichfc51d282015-08-19 13:34:18 -06002886 // check for bias argument
2887 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002888 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002889 int nonBiasArgCount = 2;
2890 if (cracked.offset)
2891 ++nonBiasArgCount;
2892 if (cracked.grad)
2893 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002894 if (cracked.lodClamp)
2895 ++nonBiasArgCount;
2896 if (sparse)
2897 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002898
2899 if ((int)arguments.size() > nonBiasArgCount)
2900 bias = true;
2901 }
2902
John Kessenicha5c33d62016-06-02 23:45:21 -06002903 // See if the sampler param should really be just the SPV image part
2904 if (cracked.fetch) {
2905 // a fetch needs to have the image extracted first
2906 if (builder.isSampledImage(params.sampler))
2907 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2908 }
2909
John Kessenichfc51d282015-08-19 13:34:18 -06002910 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002911
John Kessenichfc51d282015-08-19 13:34:18 -06002912 params.coords = arguments[1];
2913 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002914 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002915
2916 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002917 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002918 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002919 ++extraArgs;
2920 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002921 params.Dref = arguments[2];
2922 ++extraArgs;
2923 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002924 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002925 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002926 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002927 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002928 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002929 dRefComp = builder.getNumComponents(params.coords) - 1;
2930 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002931 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2932 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002933
2934 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002935 if (cracked.lod) {
2936 params.lod = arguments[2];
2937 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002938 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2939 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2940 noImplicitLod = true;
2941 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002942
2943 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002944 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002945 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002946 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002947 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002948
2949 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002950 if (cracked.grad) {
2951 params.gradX = arguments[2 + extraArgs];
2952 params.gradY = arguments[3 + extraArgs];
2953 extraArgs += 2;
2954 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002955
2956 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002957 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002958 params.offset = arguments[2 + extraArgs];
2959 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002960 } else if (cracked.offsets) {
2961 params.offsets = arguments[2 + extraArgs];
2962 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002963 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002964
2965 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002966 if (cracked.lodClamp) {
2967 params.lodClamp = arguments[2 + extraArgs];
2968 ++extraArgs;
2969 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002970
2971 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002972 if (sparse) {
2973 params.texelOut = arguments[2 + extraArgs];
2974 ++extraArgs;
2975 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002976
2977 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002978 if (bias) {
2979 params.bias = arguments[2 + extraArgs];
2980 ++extraArgs;
2981 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002982
2983 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002984 if (cracked.gather && ! sampler.shadow) {
2985 // default component is 0, if missing, otherwise an argument
2986 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002987 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002988 ++extraArgs;
2989 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002990 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002991 }
2992 }
John Kessenichfc51d282015-08-19 13:34:18 -06002993
John Kessenich65336482016-06-16 14:06:26 -06002994 // projective component (might not to move)
2995 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2996 // are divided by the last component of P."
2997 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2998 // unused components will appear after all used components."
2999 if (cracked.proj) {
3000 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3001 int projTargetComp;
3002 switch (sampler.dim) {
3003 case glslang::Esd1D: projTargetComp = 1; break;
3004 case glslang::Esd2D: projTargetComp = 2; break;
3005 case glslang::EsdRect: projTargetComp = 2; break;
3006 default: projTargetComp = projSourceComp; break;
3007 }
3008 // copy the projective coordinate if we have to
3009 if (projTargetComp != projSourceComp) {
3010 spv::Id projComp = builder.createCompositeExtract(params.coords,
3011 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3012 projSourceComp);
3013 params.coords = builder.createCompositeInsert(projComp, params.coords,
3014 builder.getTypeId(params.coords), projTargetComp);
3015 }
3016 }
3017
John Kessenich8c8505c2016-07-26 12:50:38 -06003018 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003019}
3020
3021spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3022{
3023 // Grab the function's pointer from the previously created function
3024 spv::Function* function = functionMap[node->getName().c_str()];
3025 if (! function)
3026 return 0;
3027
3028 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3029 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3030
3031 // See comments in makeFunctions() for details about the semantics for parameter passing.
3032 //
3033 // These imply we need a four step process:
3034 // 1. Evaluate the arguments
3035 // 2. Allocate and make copies of in, out, and inout arguments
3036 // 3. Make the call
3037 // 4. Copy back the results
3038
3039 // 1. Evaluate the arguments
3040 std::vector<spv::Builder::AccessChain> lValues;
3041 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003042 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003043 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003044 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003045 // build l-value
3046 builder.clearAccessChain();
3047 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003048 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003049 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07003050 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003051 // save l-value
3052 lValues.push_back(builder.getAccessChain());
3053 } else {
3054 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003055 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003056 }
3057 }
3058
3059 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3060 // copy the original into that space.
3061 //
3062 // Also, build up the list of actual arguments to pass in for the call
3063 int lValueCount = 0;
3064 int rValueCount = 0;
3065 std::vector<spv::Id> spvArgs;
3066 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003067 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003068 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07003069 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003070 builder.setAccessChain(lValues[lValueCount]);
3071 arg = builder.accessChainGetLValue();
3072 ++lValueCount;
3073 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003074 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003075 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3076 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3077 // need to copy the input into output space
3078 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003079 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003080 builder.clearAccessChain();
3081 builder.setAccessChainLValue(arg);
3082 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003083 }
3084 ++lValueCount;
3085 } else {
3086 arg = rValues[rValueCount];
3087 ++rValueCount;
3088 }
3089 spvArgs.push_back(arg);
3090 }
3091
3092 // 3. Make the call.
3093 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003094 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003095
3096 // 4. Copy back out an "out" arguments.
3097 lValueCount = 0;
3098 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003099 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003100 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3101 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3102 spv::Id copy = builder.createLoad(spvArgs[a]);
3103 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003104 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003105 }
3106 ++lValueCount;
3107 }
3108 }
3109
3110 return result;
3111}
3112
3113// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003114spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3115 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003116 spv::Id typeId, spv::Id left, spv::Id right,
3117 glslang::TBasicType typeProxy, bool reduceComparison)
3118{
Rex Xu8ff43de2016-04-22 16:51:45 +08003119 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003120#ifdef AMD_EXTENSIONS
3121 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3122#else
John Kessenich140f3df2015-06-26 16:58:36 -06003123 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003124#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003125 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003126
3127 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003128 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003129 bool comparison = false;
3130
3131 switch (op) {
3132 case glslang::EOpAdd:
3133 case glslang::EOpAddAssign:
3134 if (isFloat)
3135 binOp = spv::OpFAdd;
3136 else
3137 binOp = spv::OpIAdd;
3138 break;
3139 case glslang::EOpSub:
3140 case glslang::EOpSubAssign:
3141 if (isFloat)
3142 binOp = spv::OpFSub;
3143 else
3144 binOp = spv::OpISub;
3145 break;
3146 case glslang::EOpMul:
3147 case glslang::EOpMulAssign:
3148 if (isFloat)
3149 binOp = spv::OpFMul;
3150 else
3151 binOp = spv::OpIMul;
3152 break;
3153 case glslang::EOpVectorTimesScalar:
3154 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003155 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003156 if (builder.isVector(right))
3157 std::swap(left, right);
3158 assert(builder.isScalar(right));
3159 needMatchingVectors = false;
3160 binOp = spv::OpVectorTimesScalar;
3161 } else
3162 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003163 break;
3164 case glslang::EOpVectorTimesMatrix:
3165 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003166 binOp = spv::OpVectorTimesMatrix;
3167 break;
3168 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003169 binOp = spv::OpMatrixTimesVector;
3170 break;
3171 case glslang::EOpMatrixTimesScalar:
3172 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003173 binOp = spv::OpMatrixTimesScalar;
3174 break;
3175 case glslang::EOpMatrixTimesMatrix:
3176 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003177 binOp = spv::OpMatrixTimesMatrix;
3178 break;
3179 case glslang::EOpOuterProduct:
3180 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003181 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003182 break;
3183
3184 case glslang::EOpDiv:
3185 case glslang::EOpDivAssign:
3186 if (isFloat)
3187 binOp = spv::OpFDiv;
3188 else if (isUnsigned)
3189 binOp = spv::OpUDiv;
3190 else
3191 binOp = spv::OpSDiv;
3192 break;
3193 case glslang::EOpMod:
3194 case glslang::EOpModAssign:
3195 if (isFloat)
3196 binOp = spv::OpFMod;
3197 else if (isUnsigned)
3198 binOp = spv::OpUMod;
3199 else
3200 binOp = spv::OpSMod;
3201 break;
3202 case glslang::EOpRightShift:
3203 case glslang::EOpRightShiftAssign:
3204 if (isUnsigned)
3205 binOp = spv::OpShiftRightLogical;
3206 else
3207 binOp = spv::OpShiftRightArithmetic;
3208 break;
3209 case glslang::EOpLeftShift:
3210 case glslang::EOpLeftShiftAssign:
3211 binOp = spv::OpShiftLeftLogical;
3212 break;
3213 case glslang::EOpAnd:
3214 case glslang::EOpAndAssign:
3215 binOp = spv::OpBitwiseAnd;
3216 break;
3217 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003218 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003219 binOp = spv::OpLogicalAnd;
3220 break;
3221 case glslang::EOpInclusiveOr:
3222 case glslang::EOpInclusiveOrAssign:
3223 binOp = spv::OpBitwiseOr;
3224 break;
3225 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003226 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003227 binOp = spv::OpLogicalOr;
3228 break;
3229 case glslang::EOpExclusiveOr:
3230 case glslang::EOpExclusiveOrAssign:
3231 binOp = spv::OpBitwiseXor;
3232 break;
3233 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003234 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003235 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003236 break;
3237
3238 case glslang::EOpLessThan:
3239 case glslang::EOpGreaterThan:
3240 case glslang::EOpLessThanEqual:
3241 case glslang::EOpGreaterThanEqual:
3242 case glslang::EOpEqual:
3243 case glslang::EOpNotEqual:
3244 case glslang::EOpVectorEqual:
3245 case glslang::EOpVectorNotEqual:
3246 comparison = true;
3247 break;
3248 default:
3249 break;
3250 }
3251
John Kessenich7c1aa102015-10-15 13:29:11 -06003252 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003253 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003254 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003255 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003256 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003257
3258 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003259 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003260 builder.promoteScalar(precision, left, right);
3261
qining25262b32016-05-06 17:25:16 -04003262 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3263 addDecoration(result, noContraction);
3264 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003265 }
3266
3267 if (! comparison)
3268 return 0;
3269
John Kessenich7c1aa102015-10-15 13:29:11 -06003270 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003271
John Kessenich4583b612016-08-07 19:14:22 -06003272 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3273 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003274 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003275
3276 switch (op) {
3277 case glslang::EOpLessThan:
3278 if (isFloat)
3279 binOp = spv::OpFOrdLessThan;
3280 else if (isUnsigned)
3281 binOp = spv::OpULessThan;
3282 else
3283 binOp = spv::OpSLessThan;
3284 break;
3285 case glslang::EOpGreaterThan:
3286 if (isFloat)
3287 binOp = spv::OpFOrdGreaterThan;
3288 else if (isUnsigned)
3289 binOp = spv::OpUGreaterThan;
3290 else
3291 binOp = spv::OpSGreaterThan;
3292 break;
3293 case glslang::EOpLessThanEqual:
3294 if (isFloat)
3295 binOp = spv::OpFOrdLessThanEqual;
3296 else if (isUnsigned)
3297 binOp = spv::OpULessThanEqual;
3298 else
3299 binOp = spv::OpSLessThanEqual;
3300 break;
3301 case glslang::EOpGreaterThanEqual:
3302 if (isFloat)
3303 binOp = spv::OpFOrdGreaterThanEqual;
3304 else if (isUnsigned)
3305 binOp = spv::OpUGreaterThanEqual;
3306 else
3307 binOp = spv::OpSGreaterThanEqual;
3308 break;
3309 case glslang::EOpEqual:
3310 case glslang::EOpVectorEqual:
3311 if (isFloat)
3312 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003313 else if (isBool)
3314 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003315 else
3316 binOp = spv::OpIEqual;
3317 break;
3318 case glslang::EOpNotEqual:
3319 case glslang::EOpVectorNotEqual:
3320 if (isFloat)
3321 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003322 else if (isBool)
3323 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003324 else
3325 binOp = spv::OpINotEqual;
3326 break;
3327 default:
3328 break;
3329 }
3330
qining25262b32016-05-06 17:25:16 -04003331 if (binOp != spv::OpNop) {
3332 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3333 addDecoration(result, noContraction);
3334 return builder.setPrecision(result, precision);
3335 }
John Kessenich140f3df2015-06-26 16:58:36 -06003336
3337 return 0;
3338}
3339
John Kessenich04bb8a02015-12-12 12:28:14 -07003340//
3341// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3342// These can be any of:
3343//
3344// matrix * scalar
3345// scalar * matrix
3346// matrix * matrix linear algebraic
3347// matrix * vector
3348// vector * matrix
3349// matrix * matrix componentwise
3350// matrix op matrix op in {+, -, /}
3351// matrix op scalar op in {+, -, /}
3352// scalar op matrix op in {+, -, /}
3353//
qining25262b32016-05-06 17:25:16 -04003354spv::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 -07003355{
3356 bool firstClass = true;
3357
3358 // First, handle first-class matrix operations (* and matrix/scalar)
3359 switch (op) {
3360 case spv::OpFDiv:
3361 if (builder.isMatrix(left) && builder.isScalar(right)) {
3362 // turn matrix / scalar into a multiply...
3363 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3364 op = spv::OpMatrixTimesScalar;
3365 } else
3366 firstClass = false;
3367 break;
3368 case spv::OpMatrixTimesScalar:
3369 if (builder.isMatrix(right))
3370 std::swap(left, right);
3371 assert(builder.isScalar(right));
3372 break;
3373 case spv::OpVectorTimesMatrix:
3374 assert(builder.isVector(left));
3375 assert(builder.isMatrix(right));
3376 break;
3377 case spv::OpMatrixTimesVector:
3378 assert(builder.isMatrix(left));
3379 assert(builder.isVector(right));
3380 break;
3381 case spv::OpMatrixTimesMatrix:
3382 assert(builder.isMatrix(left));
3383 assert(builder.isMatrix(right));
3384 break;
3385 default:
3386 firstClass = false;
3387 break;
3388 }
3389
qining25262b32016-05-06 17:25:16 -04003390 if (firstClass) {
3391 spv::Id result = builder.createBinOp(op, typeId, left, right);
3392 addDecoration(result, noContraction);
3393 return builder.setPrecision(result, precision);
3394 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003395
LoopDawg592860c2016-06-09 08:57:35 -06003396 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003397 // The result type of all of them is the same type as the (a) matrix operand.
3398 // The algorithm is to:
3399 // - break the matrix(es) into vectors
3400 // - smear any scalar to a vector
3401 // - do vector operations
3402 // - make a matrix out the vector results
3403 switch (op) {
3404 case spv::OpFAdd:
3405 case spv::OpFSub:
3406 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003407 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003408 case spv::OpFMul:
3409 {
3410 // one time set up...
3411 bool leftMat = builder.isMatrix(left);
3412 bool rightMat = builder.isMatrix(right);
3413 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3414 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3415 spv::Id scalarType = builder.getScalarTypeId(typeId);
3416 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3417 std::vector<spv::Id> results;
3418 spv::Id smearVec = spv::NoResult;
3419 if (builder.isScalar(left))
3420 smearVec = builder.smearScalar(precision, left, vecType);
3421 else if (builder.isScalar(right))
3422 smearVec = builder.smearScalar(precision, right, vecType);
3423
3424 // do each vector op
3425 for (unsigned int c = 0; c < numCols; ++c) {
3426 std::vector<unsigned int> indexes;
3427 indexes.push_back(c);
3428 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3429 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003430 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3431 addDecoration(result, noContraction);
3432 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003433 }
3434
3435 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003436 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003437 }
3438 default:
3439 assert(0);
3440 return spv::NoResult;
3441 }
3442}
3443
qining25262b32016-05-06 17:25:16 -04003444spv::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 -06003445{
3446 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003447 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003448 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003449 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003450#ifdef AMD_EXTENSIONS
3451 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3452#else
Rex Xu04db3f52015-09-16 11:44:02 +08003453 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003454#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003455
3456 switch (op) {
3457 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003458 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003459 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003460 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003461 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003462 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003463 unaryOp = spv::OpSNegate;
3464 break;
3465
3466 case glslang::EOpLogicalNot:
3467 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003468 unaryOp = spv::OpLogicalNot;
3469 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003470 case glslang::EOpBitwiseNot:
3471 unaryOp = spv::OpNot;
3472 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003473
John Kessenich140f3df2015-06-26 16:58:36 -06003474 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003475 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003476 break;
3477 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003478 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003479 break;
3480 case glslang::EOpTranspose:
3481 unaryOp = spv::OpTranspose;
3482 break;
3483
3484 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003485 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003486 break;
3487 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003488 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003489 break;
3490 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003491 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003492 break;
3493 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003494 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003495 break;
3496 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003497 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003498 break;
3499 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003500 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003501 break;
3502 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003503 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003504 break;
3505 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003506 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003507 break;
3508
3509 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003510 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003511 break;
3512 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003513 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003514 break;
3515 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003516 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003517 break;
3518 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003519 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003520 break;
3521 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003522 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003523 break;
3524 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003525 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003526 break;
3527
3528 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003529 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003530 break;
3531 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003532 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003533 break;
3534
3535 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003536 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003537 break;
3538 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003539 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003540 break;
3541 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003542 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003543 break;
3544 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003545 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003546 break;
3547 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003548 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003549 break;
3550 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003551 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003552 break;
3553
3554 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003555 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003556 break;
3557 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003558 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003559 break;
3560 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003561 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003562 break;
3563 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003564 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003565 break;
3566 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003567 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003568 break;
3569 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003570 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003571 break;
3572
3573 case glslang::EOpIsNan:
3574 unaryOp = spv::OpIsNan;
3575 break;
3576 case glslang::EOpIsInf:
3577 unaryOp = spv::OpIsInf;
3578 break;
LoopDawg592860c2016-06-09 08:57:35 -06003579 case glslang::EOpIsFinite:
3580 unaryOp = spv::OpIsFinite;
3581 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003582
Rex Xucbc426e2015-12-15 16:03:10 +08003583 case glslang::EOpFloatBitsToInt:
3584 case glslang::EOpFloatBitsToUint:
3585 case glslang::EOpIntBitsToFloat:
3586 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003587 case glslang::EOpDoubleBitsToInt64:
3588 case glslang::EOpDoubleBitsToUint64:
3589 case glslang::EOpInt64BitsToDouble:
3590 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003591 unaryOp = spv::OpBitcast;
3592 break;
3593
John Kessenich140f3df2015-06-26 16:58:36 -06003594 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003595 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003596 break;
3597 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003598 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003599 break;
3600 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003601 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003602 break;
3603 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003604 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003605 break;
3606 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003607 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003608 break;
3609 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003610 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003611 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003612 case glslang::EOpPackSnorm4x8:
3613 libCall = spv::GLSLstd450PackSnorm4x8;
3614 break;
3615 case glslang::EOpUnpackSnorm4x8:
3616 libCall = spv::GLSLstd450UnpackSnorm4x8;
3617 break;
3618 case glslang::EOpPackUnorm4x8:
3619 libCall = spv::GLSLstd450PackUnorm4x8;
3620 break;
3621 case glslang::EOpUnpackUnorm4x8:
3622 libCall = spv::GLSLstd450UnpackUnorm4x8;
3623 break;
3624 case glslang::EOpPackDouble2x32:
3625 libCall = spv::GLSLstd450PackDouble2x32;
3626 break;
3627 case glslang::EOpUnpackDouble2x32:
3628 libCall = spv::GLSLstd450UnpackDouble2x32;
3629 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003630
Rex Xu8ff43de2016-04-22 16:51:45 +08003631 case glslang::EOpPackInt2x32:
3632 case glslang::EOpUnpackInt2x32:
3633 case glslang::EOpPackUint2x32:
3634 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003635 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003636 break;
3637
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003638#ifdef AMD_EXTENSIONS
3639 case glslang::EOpPackFloat2x16:
3640 case glslang::EOpUnpackFloat2x16:
3641 unaryOp = spv::OpBitcast;
3642 break;
3643#endif
3644
John Kessenich140f3df2015-06-26 16:58:36 -06003645 case glslang::EOpDPdx:
3646 unaryOp = spv::OpDPdx;
3647 break;
3648 case glslang::EOpDPdy:
3649 unaryOp = spv::OpDPdy;
3650 break;
3651 case glslang::EOpFwidth:
3652 unaryOp = spv::OpFwidth;
3653 break;
3654 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003655 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003656 unaryOp = spv::OpDPdxFine;
3657 break;
3658 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003659 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003660 unaryOp = spv::OpDPdyFine;
3661 break;
3662 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003663 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003664 unaryOp = spv::OpFwidthFine;
3665 break;
3666 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003667 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003668 unaryOp = spv::OpDPdxCoarse;
3669 break;
3670 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003671 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003672 unaryOp = spv::OpDPdyCoarse;
3673 break;
3674 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003675 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003676 unaryOp = spv::OpFwidthCoarse;
3677 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003678 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003679 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003680 libCall = spv::GLSLstd450InterpolateAtCentroid;
3681 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003682 case glslang::EOpAny:
3683 unaryOp = spv::OpAny;
3684 break;
3685 case glslang::EOpAll:
3686 unaryOp = spv::OpAll;
3687 break;
3688
3689 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003690 if (isFloat)
3691 libCall = spv::GLSLstd450FAbs;
3692 else
3693 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003694 break;
3695 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003696 if (isFloat)
3697 libCall = spv::GLSLstd450FSign;
3698 else
3699 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003700 break;
3701
John Kessenichfc51d282015-08-19 13:34:18 -06003702 case glslang::EOpAtomicCounterIncrement:
3703 case glslang::EOpAtomicCounterDecrement:
3704 case glslang::EOpAtomicCounter:
3705 {
3706 // Handle all of the atomics in one place, in createAtomicOperation()
3707 std::vector<spv::Id> operands;
3708 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003709 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003710 }
3711
John Kessenichfc51d282015-08-19 13:34:18 -06003712 case glslang::EOpBitFieldReverse:
3713 unaryOp = spv::OpBitReverse;
3714 break;
3715 case glslang::EOpBitCount:
3716 unaryOp = spv::OpBitCount;
3717 break;
3718 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003719 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003720 break;
3721 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003722 if (isUnsigned)
3723 libCall = spv::GLSLstd450FindUMsb;
3724 else
3725 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003726 break;
3727
Rex Xu574ab042016-04-14 16:53:07 +08003728 case glslang::EOpBallot:
3729 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003730 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003731 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003732 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003733#ifdef AMD_EXTENSIONS
3734 case glslang::EOpMinInvocations:
3735 case glslang::EOpMaxInvocations:
3736 case glslang::EOpAddInvocations:
3737 case glslang::EOpMinInvocationsNonUniform:
3738 case glslang::EOpMaxInvocationsNonUniform:
3739 case glslang::EOpAddInvocationsNonUniform:
3740#endif
Rex Xu51596642016-09-21 18:56:12 +08003741 {
3742 std::vector<spv::Id> operands;
3743 operands.push_back(operand);
3744 return createInvocationsOperation(op, typeId, operands, typeProxy);
3745 }
Rex Xu9d93a232016-05-05 12:30:44 +08003746
3747#ifdef AMD_EXTENSIONS
3748 case glslang::EOpMbcnt:
3749 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3750 libCall = spv::MbcntAMD;
3751 break;
3752
3753 case glslang::EOpCubeFaceIndex:
3754 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3755 libCall = spv::CubeFaceIndexAMD;
3756 break;
3757
3758 case glslang::EOpCubeFaceCoord:
3759 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3760 libCall = spv::CubeFaceCoordAMD;
3761 break;
3762#endif
Rex Xu338b1852016-05-05 20:38:33 +08003763
John Kessenich140f3df2015-06-26 16:58:36 -06003764 default:
3765 return 0;
3766 }
3767
3768 spv::Id id;
3769 if (libCall >= 0) {
3770 std::vector<spv::Id> args;
3771 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003772 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003773 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003774 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003775 }
John Kessenich140f3df2015-06-26 16:58:36 -06003776
qining25262b32016-05-06 17:25:16 -04003777 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003778 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003779}
3780
John Kessenich7a53f762016-01-20 11:19:27 -07003781// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003782spv::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 -07003783{
3784 // Handle unary operations vector by vector.
3785 // The result type is the same type as the original type.
3786 // The algorithm is to:
3787 // - break the matrix into vectors
3788 // - apply the operation to each vector
3789 // - make a matrix out the vector results
3790
3791 // get the types sorted out
3792 int numCols = builder.getNumColumns(operand);
3793 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003794 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3795 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003796 std::vector<spv::Id> results;
3797
3798 // do each vector op
3799 for (int c = 0; c < numCols; ++c) {
3800 std::vector<unsigned int> indexes;
3801 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003802 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3803 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3804 addDecoration(destVec, noContraction);
3805 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003806 }
3807
3808 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003809 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003810}
3811
Rex Xu73e3ce72016-04-27 18:48:17 +08003812spv::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 -06003813{
3814 spv::Op convOp = spv::OpNop;
3815 spv::Id zero = 0;
3816 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003817 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003818
3819 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3820
3821 switch (op) {
3822 case glslang::EOpConvIntToBool:
3823 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003824 case glslang::EOpConvInt64ToBool:
3825 case glslang::EOpConvUint64ToBool:
3826 zero = (op == glslang::EOpConvInt64ToBool ||
3827 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003828 zero = makeSmearedConstant(zero, vectorSize);
3829 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3830
3831 case glslang::EOpConvFloatToBool:
3832 zero = builder.makeFloatConstant(0.0F);
3833 zero = makeSmearedConstant(zero, vectorSize);
3834 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3835
3836 case glslang::EOpConvDoubleToBool:
3837 zero = builder.makeDoubleConstant(0.0);
3838 zero = makeSmearedConstant(zero, vectorSize);
3839 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3840
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003841#ifdef AMD_EXTENSIONS
3842 case glslang::EOpConvFloat16ToBool:
3843 zero = builder.makeFloat16Constant(0.0F);
3844 zero = makeSmearedConstant(zero, vectorSize);
3845 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3846#endif
3847
John Kessenich140f3df2015-06-26 16:58:36 -06003848 case glslang::EOpConvBoolToFloat:
3849 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003850 zero = builder.makeFloatConstant(0.0F);
3851 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06003852 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003853
John Kessenich140f3df2015-06-26 16:58:36 -06003854 case glslang::EOpConvBoolToDouble:
3855 convOp = spv::OpSelect;
3856 zero = builder.makeDoubleConstant(0.0);
3857 one = builder.makeDoubleConstant(1.0);
3858 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003859
3860#ifdef AMD_EXTENSIONS
3861 case glslang::EOpConvBoolToFloat16:
3862 convOp = spv::OpSelect;
3863 zero = builder.makeFloat16Constant(0.0F);
3864 one = builder.makeFloat16Constant(1.0F);
3865 break;
3866#endif
3867
John Kessenich140f3df2015-06-26 16:58:36 -06003868 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003869 case glslang::EOpConvBoolToInt64:
3870 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3871 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003872 convOp = spv::OpSelect;
3873 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003874
John Kessenich140f3df2015-06-26 16:58:36 -06003875 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003876 case glslang::EOpConvBoolToUint64:
3877 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3878 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003879 convOp = spv::OpSelect;
3880 break;
3881
3882 case glslang::EOpConvIntToFloat:
3883 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003884 case glslang::EOpConvInt64ToFloat:
3885 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003886#ifdef AMD_EXTENSIONS
3887 case glslang::EOpConvIntToFloat16:
3888 case glslang::EOpConvInt64ToFloat16:
3889#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003890 convOp = spv::OpConvertSToF;
3891 break;
3892
3893 case glslang::EOpConvUintToFloat:
3894 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003895 case glslang::EOpConvUint64ToFloat:
3896 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003897#ifdef AMD_EXTENSIONS
3898 case glslang::EOpConvUintToFloat16:
3899 case glslang::EOpConvUint64ToFloat16:
3900#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003901 convOp = spv::OpConvertUToF;
3902 break;
3903
3904 case glslang::EOpConvDoubleToFloat:
3905 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003906#ifdef AMD_EXTENSIONS
3907 case glslang::EOpConvDoubleToFloat16:
3908 case glslang::EOpConvFloat16ToDouble:
3909 case glslang::EOpConvFloatToFloat16:
3910 case glslang::EOpConvFloat16ToFloat:
3911#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003912 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003913 if (builder.isMatrixType(destType))
3914 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003915 break;
3916
3917 case glslang::EOpConvFloatToInt:
3918 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003919 case glslang::EOpConvFloatToInt64:
3920 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003921#ifdef AMD_EXTENSIONS
3922 case glslang::EOpConvFloat16ToInt:
3923 case glslang::EOpConvFloat16ToInt64:
3924#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003925 convOp = spv::OpConvertFToS;
3926 break;
3927
3928 case glslang::EOpConvUintToInt:
3929 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003930 case glslang::EOpConvUint64ToInt64:
3931 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003932 if (builder.isInSpecConstCodeGenMode()) {
3933 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08003934 zero = (op == glslang::EOpConvUint64ToInt64 ||
3935 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003936 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003937 // Use OpIAdd, instead of OpBitcast to do the conversion when
3938 // generating for OpSpecConstantOp instruction.
3939 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3940 }
3941 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003942 convOp = spv::OpBitcast;
3943 break;
3944
3945 case glslang::EOpConvFloatToUint:
3946 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003947 case glslang::EOpConvFloatToUint64:
3948 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003949#ifdef AMD_EXTENSIONS
3950 case glslang::EOpConvFloat16ToUint:
3951 case glslang::EOpConvFloat16ToUint64:
3952#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003953 convOp = spv::OpConvertFToU;
3954 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003955
3956 case glslang::EOpConvIntToInt64:
3957 case glslang::EOpConvInt64ToInt:
3958 convOp = spv::OpSConvert;
3959 break;
3960
3961 case glslang::EOpConvUintToUint64:
3962 case glslang::EOpConvUint64ToUint:
3963 convOp = spv::OpUConvert;
3964 break;
3965
3966 case glslang::EOpConvIntToUint64:
3967 case glslang::EOpConvInt64ToUint:
3968 case glslang::EOpConvUint64ToInt:
3969 case glslang::EOpConvUintToInt64:
3970 // OpSConvert/OpUConvert + OpBitCast
3971 switch (op) {
3972 case glslang::EOpConvIntToUint64:
3973 convOp = spv::OpSConvert;
3974 type = builder.makeIntType(64);
3975 break;
3976 case glslang::EOpConvInt64ToUint:
3977 convOp = spv::OpSConvert;
3978 type = builder.makeIntType(32);
3979 break;
3980 case glslang::EOpConvUint64ToInt:
3981 convOp = spv::OpUConvert;
3982 type = builder.makeUintType(32);
3983 break;
3984 case glslang::EOpConvUintToInt64:
3985 convOp = spv::OpUConvert;
3986 type = builder.makeUintType(64);
3987 break;
3988 default:
3989 assert(0);
3990 break;
3991 }
3992
3993 if (vectorSize > 0)
3994 type = builder.makeVectorType(type, vectorSize);
3995
3996 operand = builder.createUnaryOp(convOp, type, operand);
3997
3998 if (builder.isInSpecConstCodeGenMode()) {
3999 // Build zero scalar or vector for OpIAdd.
4000 zero = (op == glslang::EOpConvIntToUint64 ||
4001 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4002 zero = makeSmearedConstant(zero, vectorSize);
4003 // Use OpIAdd, instead of OpBitcast to do the conversion when
4004 // generating for OpSpecConstantOp instruction.
4005 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4006 }
4007 // For normal run-time conversion instruction, use OpBitcast.
4008 convOp = spv::OpBitcast;
4009 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004010 default:
4011 break;
4012 }
4013
4014 spv::Id result = 0;
4015 if (convOp == spv::OpNop)
4016 return result;
4017
4018 if (convOp == spv::OpSelect) {
4019 zero = makeSmearedConstant(zero, vectorSize);
4020 one = makeSmearedConstant(one, vectorSize);
4021 result = builder.createTriOp(convOp, destType, operand, one, zero);
4022 } else
4023 result = builder.createUnaryOp(convOp, destType, operand);
4024
John Kessenich32cfd492016-02-02 12:37:46 -07004025 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004026}
4027
4028spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4029{
4030 if (vectorSize == 0)
4031 return constant;
4032
4033 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4034 std::vector<spv::Id> components;
4035 for (int c = 0; c < vectorSize; ++c)
4036 components.push_back(constant);
4037 return builder.makeCompositeConstant(vectorTypeId, components);
4038}
4039
John Kessenich426394d2015-07-23 10:22:48 -06004040// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004041spv::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 -06004042{
4043 spv::Op opCode = spv::OpNop;
4044
4045 switch (op) {
4046 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004047 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004048 opCode = spv::OpAtomicIAdd;
4049 break;
4050 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004051 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004052 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004053 break;
4054 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004055 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004056 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004057 break;
4058 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004059 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004060 opCode = spv::OpAtomicAnd;
4061 break;
4062 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004063 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004064 opCode = spv::OpAtomicOr;
4065 break;
4066 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004067 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004068 opCode = spv::OpAtomicXor;
4069 break;
4070 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004071 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004072 opCode = spv::OpAtomicExchange;
4073 break;
4074 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004075 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004076 opCode = spv::OpAtomicCompareExchange;
4077 break;
4078 case glslang::EOpAtomicCounterIncrement:
4079 opCode = spv::OpAtomicIIncrement;
4080 break;
4081 case glslang::EOpAtomicCounterDecrement:
4082 opCode = spv::OpAtomicIDecrement;
4083 break;
4084 case glslang::EOpAtomicCounter:
4085 opCode = spv::OpAtomicLoad;
4086 break;
4087 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004088 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004089 break;
4090 }
4091
4092 // Sort out the operands
4093 // - mapping from glslang -> SPV
4094 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004095 // - compare-exchange swaps the value and comparator
4096 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004097 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4098 auto opIt = operands.begin(); // walk the glslang operands
4099 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004100 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4101 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4102 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004103 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4104 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004105 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004106 spvAtomicOperands.push_back(*(opIt + 1));
4107 spvAtomicOperands.push_back(*opIt);
4108 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004109 }
John Kessenich426394d2015-07-23 10:22:48 -06004110
John Kessenich3e60a6f2015-09-14 22:45:16 -06004111 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004112 for (; opIt != operands.end(); ++opIt)
4113 spvAtomicOperands.push_back(*opIt);
4114
4115 return builder.createOp(opCode, typeId, spvAtomicOperands);
4116}
4117
John Kessenich91cef522016-05-05 16:45:40 -06004118// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004119spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004120{
Rex Xu9d93a232016-05-05 12:30:44 +08004121 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004122#ifdef AMD_EXTENSIONS
4123 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4124#else
Rex Xu9d93a232016-05-05 12:30:44 +08004125 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004126#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004127
Rex Xu51596642016-09-21 18:56:12 +08004128 spv::Op opCode = spv::OpNop;
John Kessenich91cef522016-05-05 16:45:40 -06004129
Rex Xu51596642016-09-21 18:56:12 +08004130 std::vector<spv::Id> spvGroupOperands;
4131 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation) {
4132 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4133 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
4134 } else {
4135 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08004136 if (op == glslang::EOpMinInvocationsNonUniform ||
4137 op == glslang::EOpMaxInvocationsNonUniform ||
4138 op == glslang::EOpAddInvocationsNonUniform)
4139 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08004140
4141 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004142#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +08004143 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
4144 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
4145 spvGroupOperands.push_back(spv::GroupOperationReduce);
Rex Xu9d93a232016-05-05 12:30:44 +08004146#endif
Rex Xu51596642016-09-21 18:56:12 +08004147 }
4148
4149 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4150 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004151
4152 switch (op) {
4153 case glslang::EOpAnyInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004154 opCode = spv::OpGroupAny;
4155 break;
John Kessenich91cef522016-05-05 16:45:40 -06004156 case glslang::EOpAllInvocations:
Rex Xu51596642016-09-21 18:56:12 +08004157 opCode = spv::OpGroupAll;
4158 break;
John Kessenich91cef522016-05-05 16:45:40 -06004159 case glslang::EOpAllInvocationsEqual:
4160 {
Rex Xu51596642016-09-21 18:56:12 +08004161 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, spvGroupOperands);
4162 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004163
4164 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
4165 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
4166 }
Rex Xu51596642016-09-21 18:56:12 +08004167
4168 case glslang::EOpReadInvocation:
4169 opCode = spv::OpGroupBroadcast;
Rex Xub7072052016-09-26 15:53:40 +08004170 if (builder.isVectorType(typeId))
4171 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004172 break;
4173 case glslang::EOpReadFirstInvocation:
4174 opCode = spv::OpSubgroupFirstInvocationKHR;
4175 break;
4176 case glslang::EOpBallot:
4177 {
4178 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4179 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4180 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4181 //
4182 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4183 //
4184 spv::Id uintType = builder.makeUintType(32);
4185 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4186 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4187
4188 std::vector<spv::Id> components;
4189 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4190 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4191
4192 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4193 return builder.createUnaryOp(spv::OpBitcast, typeId,
4194 builder.createCompositeConstruct(uvec2Type, components));
4195 }
4196
Rex Xu9d93a232016-05-05 12:30:44 +08004197#ifdef AMD_EXTENSIONS
4198 case glslang::EOpMinInvocations:
4199 case glslang::EOpMaxInvocations:
4200 case glslang::EOpAddInvocations:
Rex Xu9d93a232016-05-05 12:30:44 +08004201 if (op == glslang::EOpMinInvocations) {
4202 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004203 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004204 else {
4205 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004206 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004207 else
Rex Xu51596642016-09-21 18:56:12 +08004208 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004209 }
4210 } else if (op == glslang::EOpMaxInvocations) {
4211 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004212 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004213 else {
4214 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004215 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004216 else
Rex Xu51596642016-09-21 18:56:12 +08004217 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004218 }
4219 } else {
4220 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004221 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004222 else
Rex Xu51596642016-09-21 18:56:12 +08004223 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004224 }
4225
Rex Xu2bbbe062016-08-23 15:41:05 +08004226 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004227 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004228
4229 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004230 case glslang::EOpMinInvocationsNonUniform:
4231 case glslang::EOpMaxInvocationsNonUniform:
4232 case glslang::EOpAddInvocationsNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004233 if (op == glslang::EOpMinInvocationsNonUniform) {
4234 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004235 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004236 else {
4237 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004238 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004239 else
Rex Xu51596642016-09-21 18:56:12 +08004240 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004241 }
4242 }
4243 else if (op == glslang::EOpMaxInvocationsNonUniform) {
4244 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004245 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004246 else {
4247 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004248 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004249 else
Rex Xu51596642016-09-21 18:56:12 +08004250 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004251 }
4252 }
4253 else {
4254 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004255 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004256 else
Rex Xu51596642016-09-21 18:56:12 +08004257 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004258 }
4259
Rex Xu2bbbe062016-08-23 15:41:05 +08004260 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004261 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004262
4263 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004264#endif
John Kessenich91cef522016-05-05 16:45:40 -06004265 default:
4266 logger->missingFunctionality("invocation operation");
4267 return spv::NoResult;
4268 }
Rex Xu51596642016-09-21 18:56:12 +08004269
4270 assert(opCode != spv::OpNop);
4271 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004272}
4273
Rex Xu2bbbe062016-08-23 15:41:05 +08004274// Create group invocation operations on a vector
Rex Xub7072052016-09-26 15:53:40 +08004275spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004276{
Rex Xub7072052016-09-26 15:53:40 +08004277#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004278 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4279 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004280 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004281 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4282 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4283 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004284#else
4285 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4286 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
4287 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast);
4288#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004289
4290 // Handle group invocation operations scalar by scalar.
4291 // The result type is the same type as the original type.
4292 // The algorithm is to:
4293 // - break the vector into scalars
4294 // - apply the operation to each scalar
4295 // - make a vector out the scalar results
4296
4297 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004298 int numComponents = builder.getNumComponents(operands[0]);
4299 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004300 std::vector<spv::Id> results;
4301
4302 // do each scalar op
4303 for (int comp = 0; comp < numComponents; ++comp) {
4304 std::vector<unsigned int> indexes;
4305 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004306 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xu2bbbe062016-08-23 15:41:05 +08004307
Rex Xub7072052016-09-26 15:53:40 +08004308 std::vector<spv::Id> spvGroupOperands;
4309 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
4310 if (op == spv::OpGroupBroadcast) {
4311 spvGroupOperands.push_back(scalar);
4312 spvGroupOperands.push_back(operands[1]);
4313 } else {
4314 spvGroupOperands.push_back(spv::GroupOperationReduce);
4315 spvGroupOperands.push_back(scalar);
4316 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004317
Rex Xub7072052016-09-26 15:53:40 +08004318 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004319 }
4320
4321 // put the pieces together
4322 return builder.createCompositeConstruct(typeId, results);
4323}
Rex Xu2bbbe062016-08-23 15:41:05 +08004324
John Kessenich5e4b1242015-08-06 22:53:06 -06004325spv::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 -06004326{
Rex Xu8ff43de2016-04-22 16:51:45 +08004327 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004328#ifdef AMD_EXTENSIONS
4329 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4330#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004331 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004332#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004333
John Kessenich140f3df2015-06-26 16:58:36 -06004334 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004335 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004336 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004337 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004338 spv::Id typeId0 = 0;
4339 if (consumedOperands > 0)
4340 typeId0 = builder.getTypeId(operands[0]);
4341 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004342
4343 switch (op) {
4344 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004345 if (isFloat)
4346 libCall = spv::GLSLstd450FMin;
4347 else if (isUnsigned)
4348 libCall = spv::GLSLstd450UMin;
4349 else
4350 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004351 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004352 break;
4353 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004354 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004355 break;
4356 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004357 if (isFloat)
4358 libCall = spv::GLSLstd450FMax;
4359 else if (isUnsigned)
4360 libCall = spv::GLSLstd450UMax;
4361 else
4362 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004363 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004364 break;
4365 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004366 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004367 break;
4368 case glslang::EOpDot:
4369 opCode = spv::OpDot;
4370 break;
4371 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004372 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004373 break;
4374
4375 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004376 if (isFloat)
4377 libCall = spv::GLSLstd450FClamp;
4378 else if (isUnsigned)
4379 libCall = spv::GLSLstd450UClamp;
4380 else
4381 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004382 builder.promoteScalar(precision, operands.front(), operands[1]);
4383 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004384 break;
4385 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004386 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4387 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004388 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004389 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004390 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004391 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004392 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004393 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004394 break;
4395 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004396 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004397 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004398 break;
4399 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004400 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004401 builder.promoteScalar(precision, operands[0], operands[2]);
4402 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004403 break;
4404
4405 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004406 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004407 break;
4408 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004409 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004410 break;
4411 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004412 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004413 break;
4414 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004415 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004416 break;
4417 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004418 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004419 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004420 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004421 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004422 libCall = spv::GLSLstd450InterpolateAtSample;
4423 break;
4424 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004425 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004426 libCall = spv::GLSLstd450InterpolateAtOffset;
4427 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004428 case glslang::EOpAddCarry:
4429 opCode = spv::OpIAddCarry;
4430 typeId = builder.makeStructResultType(typeId0, typeId0);
4431 consumedOperands = 2;
4432 break;
4433 case glslang::EOpSubBorrow:
4434 opCode = spv::OpISubBorrow;
4435 typeId = builder.makeStructResultType(typeId0, typeId0);
4436 consumedOperands = 2;
4437 break;
4438 case glslang::EOpUMulExtended:
4439 opCode = spv::OpUMulExtended;
4440 typeId = builder.makeStructResultType(typeId0, typeId0);
4441 consumedOperands = 2;
4442 break;
4443 case glslang::EOpIMulExtended:
4444 opCode = spv::OpSMulExtended;
4445 typeId = builder.makeStructResultType(typeId0, typeId0);
4446 consumedOperands = 2;
4447 break;
4448 case glslang::EOpBitfieldExtract:
4449 if (isUnsigned)
4450 opCode = spv::OpBitFieldUExtract;
4451 else
4452 opCode = spv::OpBitFieldSExtract;
4453 break;
4454 case glslang::EOpBitfieldInsert:
4455 opCode = spv::OpBitFieldInsert;
4456 break;
4457
4458 case glslang::EOpFma:
4459 libCall = spv::GLSLstd450Fma;
4460 break;
4461 case glslang::EOpFrexp:
4462 libCall = spv::GLSLstd450FrexpStruct;
4463 if (builder.getNumComponents(operands[0]) == 1)
4464 frexpIntType = builder.makeIntegerType(32, true);
4465 else
4466 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4467 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4468 consumedOperands = 1;
4469 break;
4470 case glslang::EOpLdexp:
4471 libCall = spv::GLSLstd450Ldexp;
4472 break;
4473
Rex Xu574ab042016-04-14 16:53:07 +08004474 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004475 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004476
Rex Xu9d93a232016-05-05 12:30:44 +08004477#ifdef AMD_EXTENSIONS
4478 case glslang::EOpSwizzleInvocations:
4479 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4480 libCall = spv::SwizzleInvocationsAMD;
4481 break;
4482 case glslang::EOpSwizzleInvocationsMasked:
4483 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4484 libCall = spv::SwizzleInvocationsMaskedAMD;
4485 break;
4486 case glslang::EOpWriteInvocation:
4487 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4488 libCall = spv::WriteInvocationAMD;
4489 break;
4490
4491 case glslang::EOpMin3:
4492 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4493 if (isFloat)
4494 libCall = spv::FMin3AMD;
4495 else {
4496 if (isUnsigned)
4497 libCall = spv::UMin3AMD;
4498 else
4499 libCall = spv::SMin3AMD;
4500 }
4501 break;
4502 case glslang::EOpMax3:
4503 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4504 if (isFloat)
4505 libCall = spv::FMax3AMD;
4506 else {
4507 if (isUnsigned)
4508 libCall = spv::UMax3AMD;
4509 else
4510 libCall = spv::SMax3AMD;
4511 }
4512 break;
4513 case glslang::EOpMid3:
4514 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4515 if (isFloat)
4516 libCall = spv::FMid3AMD;
4517 else {
4518 if (isUnsigned)
4519 libCall = spv::UMid3AMD;
4520 else
4521 libCall = spv::SMid3AMD;
4522 }
4523 break;
4524
4525 case glslang::EOpInterpolateAtVertex:
4526 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4527 libCall = spv::InterpolateAtVertexAMD;
4528 break;
4529#endif
4530
John Kessenich140f3df2015-06-26 16:58:36 -06004531 default:
4532 return 0;
4533 }
4534
4535 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004536 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004537 // Use an extended instruction from the standard library.
4538 // Construct the call arguments, without modifying the original operands vector.
4539 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4540 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004541 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004542 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004543 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004544 case 0:
4545 // should all be handled by visitAggregate and createNoArgOperation
4546 assert(0);
4547 return 0;
4548 case 1:
4549 // should all be handled by createUnaryOperation
4550 assert(0);
4551 return 0;
4552 case 2:
4553 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4554 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004555 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004556 // anything 3 or over doesn't have l-value operands, so all should be consumed
4557 assert(consumedOperands == operands.size());
4558 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004559 break;
4560 }
4561 }
4562
John Kessenich55e7d112015-11-15 21:33:39 -07004563 // Decode the return types that were structures
4564 switch (op) {
4565 case glslang::EOpAddCarry:
4566 case glslang::EOpSubBorrow:
4567 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4568 id = builder.createCompositeExtract(id, typeId0, 0);
4569 break;
4570 case glslang::EOpUMulExtended:
4571 case glslang::EOpIMulExtended:
4572 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4573 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4574 break;
4575 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004576 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004577 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4578 id = builder.createCompositeExtract(id, typeId0, 0);
4579 break;
4580 default:
4581 break;
4582 }
4583
John Kessenich32cfd492016-02-02 12:37:46 -07004584 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004585}
4586
Rex Xu9d93a232016-05-05 12:30:44 +08004587// Intrinsics with no arguments (or no return value, and no precision).
4588spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004589{
4590 // TODO: get the barrier operands correct
4591
4592 switch (op) {
4593 case glslang::EOpEmitVertex:
4594 builder.createNoResultOp(spv::OpEmitVertex);
4595 return 0;
4596 case glslang::EOpEndPrimitive:
4597 builder.createNoResultOp(spv::OpEndPrimitive);
4598 return 0;
4599 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004600 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004601 return 0;
4602 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004603 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004604 return 0;
4605 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004606 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004607 return 0;
4608 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004609 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004610 return 0;
4611 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004612 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004613 return 0;
4614 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004615 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004616 return 0;
4617 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004618 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004619 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004620 case glslang::EOpAllMemoryBarrierWithGroupSync:
4621 // Control barrier with non-"None" semantic is also a memory barrier.
4622 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4623 return 0;
4624 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4625 // Control barrier with non-"None" semantic is also a memory barrier.
4626 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4627 return 0;
4628 case glslang::EOpWorkgroupMemoryBarrier:
4629 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4630 return 0;
4631 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4632 // Control barrier with non-"None" semantic is also a memory barrier.
4633 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4634 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004635#ifdef AMD_EXTENSIONS
4636 case glslang::EOpTime:
4637 {
4638 std::vector<spv::Id> args; // Dummy arguments
4639 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4640 return builder.setPrecision(id, precision);
4641 }
4642#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004643 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004644 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004645 return 0;
4646 }
4647}
4648
4649spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4650{
John Kessenich2f273362015-07-18 22:34:27 -06004651 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004652 spv::Id id;
4653 if (symbolValues.end() != iter) {
4654 id = iter->second;
4655 return id;
4656 }
4657
4658 // it was not found, create it
4659 id = createSpvVariable(symbol);
4660 symbolValues[symbol->getId()] = id;
4661
Rex Xuc884b4a2016-06-29 15:03:44 +08004662 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004663 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004664 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004665 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004666 if (symbol->getType().getQualifier().hasSpecConstantId())
4667 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004668 if (symbol->getQualifier().hasIndex())
4669 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4670 if (symbol->getQualifier().hasComponent())
4671 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4672 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004673 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004674 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004675 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004676 if (symbol->getQualifier().hasXfbBuffer())
4677 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4678 if (symbol->getQualifier().hasXfbOffset())
4679 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4680 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004681 // atomic counters use this:
4682 if (symbol->getQualifier().hasOffset())
4683 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004684 }
4685
scygan2c864272016-05-18 18:09:17 +02004686 if (symbol->getQualifier().hasLocation())
4687 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004688 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004689 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004690 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004691 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004692 }
John Kessenich140f3df2015-06-26 16:58:36 -06004693 if (symbol->getQualifier().hasSet())
4694 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004695 else if (IsDescriptorResource(symbol->getType())) {
4696 // default to 0
4697 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4698 }
John Kessenich140f3df2015-06-26 16:58:36 -06004699 if (symbol->getQualifier().hasBinding())
4700 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004701 if (symbol->getQualifier().hasAttachment())
4702 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004703 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004704 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004705 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004706 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004707 if (symbol->getQualifier().hasXfbBuffer())
4708 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4709 }
4710
Rex Xu1da878f2016-02-21 20:59:01 +08004711 if (symbol->getType().isImage()) {
4712 std::vector<spv::Decoration> memory;
4713 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4714 for (unsigned int i = 0; i < memory.size(); ++i)
4715 addDecoration(id, memory[i]);
4716 }
4717
John Kessenich140f3df2015-06-26 16:58:36 -06004718 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004719 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004720 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004721 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004722
John Kessenich140f3df2015-06-26 16:58:36 -06004723 return id;
4724}
4725
John Kessenich55e7d112015-11-15 21:33:39 -07004726// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004727void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4728{
John Kessenich4016e382016-07-15 11:53:56 -06004729 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004730 builder.addDecoration(id, dec);
4731}
4732
John Kessenich55e7d112015-11-15 21:33:39 -07004733// If 'dec' is valid, add a one-operand decoration to an object
4734void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4735{
John Kessenich4016e382016-07-15 11:53:56 -06004736 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004737 builder.addDecoration(id, dec, value);
4738}
4739
4740// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004741void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4742{
John Kessenich4016e382016-07-15 11:53:56 -06004743 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004744 builder.addMemberDecoration(id, (unsigned)member, dec);
4745}
4746
John Kessenich92187592016-02-01 13:45:25 -07004747// If 'dec' is valid, add a one-operand decoration to a struct member
4748void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4749{
John Kessenich4016e382016-07-15 11:53:56 -06004750 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004751 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4752}
4753
John Kessenich55e7d112015-11-15 21:33:39 -07004754// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004755// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004756//
4757// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4758//
4759// Recursively walk the nodes. The nodes form a tree whose leaves are
4760// regular constants, which themselves are trees that createSpvConstant()
4761// recursively walks. So, this function walks the "top" of the tree:
4762// - emit specialization constant-building instructions for specConstant
4763// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004764spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004765{
John Kessenich7cc0e282016-03-20 00:46:02 -06004766 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004767
qining4f4bb812016-04-03 23:55:17 -04004768 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004769 if (! node.getQualifier().specConstant) {
4770 // hand off to the non-spec-constant path
4771 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4772 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004773 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004774 nextConst, false);
4775 }
4776
4777 // We now know we have a specialization constant to build
4778
John Kessenichd94c0032016-05-30 19:29:40 -06004779 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004780 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4781 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4782 std::vector<spv::Id> dimConstId;
4783 for (int dim = 0; dim < 3; ++dim) {
4784 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4785 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4786 if (specConst)
4787 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4788 }
4789 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4790 }
4791
4792 // An AST node labelled as specialization constant should be a symbol node.
4793 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4794 if (auto* sn = node.getAsSymbolNode()) {
4795 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004796 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4797 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4798 // will set the builder into spec constant op instruction generating mode.
4799 sub_tree->traverse(this);
4800 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004801 } else if (auto* const_union_array = &sn->getConstArray()){
4802 int nextConst = 0;
4803 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004804 }
4805 }
qining4f4bb812016-04-03 23:55:17 -04004806
4807 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4808 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004809 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004810 exit(1);
4811 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004812}
4813
John Kessenich140f3df2015-06-26 16:58:36 -06004814// Use 'consts' as the flattened glslang source of scalar constants to recursively
4815// build the aggregate SPIR-V constant.
4816//
4817// If there are not enough elements present in 'consts', 0 will be substituted;
4818// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4819//
qining08408382016-03-21 09:51:37 -04004820spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004821{
4822 // vector of constants for SPIR-V
4823 std::vector<spv::Id> spvConsts;
4824
4825 // Type is used for struct and array constants
4826 spv::Id typeId = convertGlslangToSpvType(glslangType);
4827
4828 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004829 glslang::TType elementType(glslangType, 0);
4830 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004831 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004832 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004833 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004834 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004835 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004836 } else if (glslangType.getStruct()) {
4837 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4838 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004839 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004840 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004841 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4842 bool zero = nextConst >= consts.size();
4843 switch (glslangType.getBasicType()) {
4844 case glslang::EbtInt:
4845 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4846 break;
4847 case glslang::EbtUint:
4848 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4849 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004850 case glslang::EbtInt64:
4851 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4852 break;
4853 case glslang::EbtUint64:
4854 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4855 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004856 case glslang::EbtFloat:
4857 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4858 break;
4859 case glslang::EbtDouble:
4860 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4861 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004862#ifdef AMD_EXTENSIONS
4863 case glslang::EbtFloat16:
4864 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4865 break;
4866#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004867 case glslang::EbtBool:
4868 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4869 break;
4870 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004871 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004872 break;
4873 }
4874 ++nextConst;
4875 }
4876 } else {
4877 // we have a non-aggregate (scalar) constant
4878 bool zero = nextConst >= consts.size();
4879 spv::Id scalar = 0;
4880 switch (glslangType.getBasicType()) {
4881 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004882 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004883 break;
4884 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004885 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004886 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004887 case glslang::EbtInt64:
4888 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4889 break;
4890 case glslang::EbtUint64:
4891 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4892 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004893 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004894 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004895 break;
4896 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004897 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004898 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004899#ifdef AMD_EXTENSIONS
4900 case glslang::EbtFloat16:
4901 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
4902 break;
4903#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004904 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004905 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004906 break;
4907 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004908 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004909 break;
4910 }
4911 ++nextConst;
4912 return scalar;
4913 }
4914
4915 return builder.makeCompositeConstant(typeId, spvConsts);
4916}
4917
John Kessenich7c1aa102015-10-15 13:29:11 -06004918// Return true if the node is a constant or symbol whose reading has no
4919// non-trivial observable cost or effect.
4920bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4921{
4922 // don't know what this is
4923 if (node == nullptr)
4924 return false;
4925
4926 // a constant is safe
4927 if (node->getAsConstantUnion() != nullptr)
4928 return true;
4929
4930 // not a symbol means non-trivial
4931 if (node->getAsSymbolNode() == nullptr)
4932 return false;
4933
4934 // a symbol, depends on what's being read
4935 switch (node->getType().getQualifier().storage) {
4936 case glslang::EvqTemporary:
4937 case glslang::EvqGlobal:
4938 case glslang::EvqIn:
4939 case glslang::EvqInOut:
4940 case glslang::EvqConst:
4941 case glslang::EvqConstReadOnly:
4942 case glslang::EvqUniform:
4943 return true;
4944 default:
4945 return false;
4946 }
qining25262b32016-05-06 17:25:16 -04004947}
John Kessenich7c1aa102015-10-15 13:29:11 -06004948
4949// A node is trivial if it is a single operation with no side effects.
4950// Error on the side of saying non-trivial.
4951// Return true if trivial.
4952bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4953{
4954 if (node == nullptr)
4955 return false;
4956
4957 // symbols and constants are trivial
4958 if (isTrivialLeaf(node))
4959 return true;
4960
4961 // otherwise, it needs to be a simple operation or one or two leaf nodes
4962
4963 // not a simple operation
4964 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4965 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4966 if (binaryNode == nullptr && unaryNode == nullptr)
4967 return false;
4968
4969 // not on leaf nodes
4970 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4971 return false;
4972
4973 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4974 return false;
4975 }
4976
4977 switch (node->getAsOperator()->getOp()) {
4978 case glslang::EOpLogicalNot:
4979 case glslang::EOpConvIntToBool:
4980 case glslang::EOpConvUintToBool:
4981 case glslang::EOpConvFloatToBool:
4982 case glslang::EOpConvDoubleToBool:
4983 case glslang::EOpEqual:
4984 case glslang::EOpNotEqual:
4985 case glslang::EOpLessThan:
4986 case glslang::EOpGreaterThan:
4987 case glslang::EOpLessThanEqual:
4988 case glslang::EOpGreaterThanEqual:
4989 case glslang::EOpIndexDirect:
4990 case glslang::EOpIndexDirectStruct:
4991 case glslang::EOpLogicalXor:
4992 case glslang::EOpAny:
4993 case glslang::EOpAll:
4994 return true;
4995 default:
4996 return false;
4997 }
4998}
4999
5000// Emit short-circuiting code, where 'right' is never evaluated unless
5001// the left side is true (for &&) or false (for ||).
5002spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5003{
5004 spv::Id boolTypeId = builder.makeBoolType();
5005
5006 // emit left operand
5007 builder.clearAccessChain();
5008 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005009 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005010
5011 // Operands to accumulate OpPhi operands
5012 std::vector<spv::Id> phiOperands;
5013 // accumulate left operand's phi information
5014 phiOperands.push_back(leftId);
5015 phiOperands.push_back(builder.getBuildPoint()->getId());
5016
5017 // Make the two kinds of operation symmetric with a "!"
5018 // || => emit "if (! left) result = right"
5019 // && => emit "if ( left) result = right"
5020 //
5021 // TODO: this runtime "not" for || could be avoided by adding functionality
5022 // to 'builder' to have an "else" without an "then"
5023 if (op == glslang::EOpLogicalOr)
5024 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5025
5026 // make an "if" based on the left value
5027 spv::Builder::If ifBuilder(leftId, builder);
5028
5029 // emit right operand as the "then" part of the "if"
5030 builder.clearAccessChain();
5031 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005032 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005033
5034 // accumulate left operand's phi information
5035 phiOperands.push_back(rightId);
5036 phiOperands.push_back(builder.getBuildPoint()->getId());
5037
5038 // finish the "if"
5039 ifBuilder.makeEndIf();
5040
5041 // phi together the two results
5042 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5043}
5044
Rex Xu9d93a232016-05-05 12:30:44 +08005045// Return type Id of the imported set of extended instructions corresponds to the name.
5046// Import this set if it has not been imported yet.
5047spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5048{
5049 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5050 return extBuiltinMap[name];
5051 else {
Rex Xu51596642016-09-21 18:56:12 +08005052 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005053 spv::Id extBuiltins = builder.import(name);
5054 extBuiltinMap[name] = extBuiltins;
5055 return extBuiltins;
5056 }
5057}
5058
John Kessenich140f3df2015-06-26 16:58:36 -06005059}; // end anonymous namespace
5060
5061namespace glslang {
5062
John Kessenich68d78fd2015-07-12 19:28:10 -06005063void GetSpirvVersion(std::string& version)
5064{
John Kessenich9e55f632015-07-15 10:03:39 -06005065 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005066 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005067 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005068 version = buf;
5069}
5070
John Kessenich140f3df2015-06-26 16:58:36 -06005071// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005072void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005073{
5074 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005075 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06005076 for (int i = 0; i < (int)spirv.size(); ++i) {
5077 unsigned int word = spirv[i];
5078 out.write((const char*)&word, 4);
5079 }
5080 out.close();
5081}
5082
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005083// Write SPIR-V out to a text file with 32-bit hexadecimal words
5084void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
5085{
5086 std::ofstream out;
5087 out.open(baseName, std::ios::binary | std::ios::out);
5088 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
5089 const int WORDS_PER_LINE = 8;
5090 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5091 out << "\t";
5092 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5093 const unsigned int word = spirv[i + j];
5094 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5095 if (i + j + 1 < (int)spirv.size()) {
5096 out << ",";
5097 }
5098 }
5099 out << std::endl;
5100 }
5101 out.close();
5102}
5103
John Kessenich140f3df2015-06-26 16:58:36 -06005104//
5105// Set up the glslang traversal
5106//
5107void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5108{
Lei Zhang17535f72016-05-04 15:55:59 -04005109 spv::SpvBuildLogger logger;
5110 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005111}
5112
Lei Zhang17535f72016-05-04 15:55:59 -04005113void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005114{
John Kessenich140f3df2015-06-26 16:58:36 -06005115 TIntermNode* root = intermediate.getTreeRoot();
5116
5117 if (root == 0)
5118 return;
5119
5120 glslang::GetThreadPoolAllocator().push();
5121
Lei Zhang17535f72016-05-04 15:55:59 -04005122 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005123
5124 root->traverse(&it);
5125
5126 it.dumpSpv(spirv);
5127
5128 glslang::GetThreadPoolAllocator().pop();
5129}
5130
5131}; // end namespace glslang