blob: 31f7aabb926485cde51cf2e2ae674982c2e40f5b [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
John Kessenich927608b2017-01-06 12:34:14 -070023// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
Lei Zhang17535f72016-05-04 15:55:59 -0400104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
steve-lunargf1709e72017-05-02 20:14:50 -0600125 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600126 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600127 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
128 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600129 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
130 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
131 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600132 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700133 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600134 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600135 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
136 glslang::TLayoutPacking, const glslang::TQualifier&);
137 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
138 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700139 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700140 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800141 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600142 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700143 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700144 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
145 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
146 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100147 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600148
John Kessenich6fccb3c2016-09-19 16:01:41 -0600149 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600150 void makeFunctions(const glslang::TIntermSequence&);
151 void makeGlobalInitializers(const glslang::TIntermSequence&);
152 void visitFunctions(const glslang::TIntermSequence&);
153 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800154 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600155 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
156 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600157 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
158
qining25262b32016-05-06 17:25:16 -0400159 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
160 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
161 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800162 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800163 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600164 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800165 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800166 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800167 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600168 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800169 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600170 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
171 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700172 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600173 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700174 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400175 spv::Id createSpvConstant(const glslang::TIntermTyped&);
176 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600177 bool isTrivialLeaf(const glslang::TIntermTyped* node);
178 bool isTrivial(const glslang::TIntermTyped* node);
179 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800180 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600181
182 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600183 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700184 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600185 int sequenceDepth;
186
Lei Zhang17535f72016-05-04 15:55:59 -0400187 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400188
John Kessenich140f3df2015-06-26 16:58:36 -0600189 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
190 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700191 bool inEntryPoint;
192 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700193 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700194 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600195 const glslang::TIntermediate* glslangIntermediate;
196 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800197 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600198
John Kessenich2f273362015-07-18 22:34:27 -0600199 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600200 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600201 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700202 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600203 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600204 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600205};
206
207//
208// Helper functions for translating glslang representations to SPIR-V enumerants.
209//
210
211// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700212spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600213{
John Kessenich66e2faf2016-03-12 18:34:36 -0700214 switch (source) {
215 case glslang::EShSourceGlsl:
216 switch (profile) {
217 case ENoProfile:
218 case ECoreProfile:
219 case ECompatibilityProfile:
220 return spv::SourceLanguageGLSL;
221 case EEsProfile:
222 return spv::SourceLanguageESSL;
223 default:
224 return spv::SourceLanguageUnknown;
225 }
226 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600227 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600228 default:
229 return spv::SourceLanguageUnknown;
230 }
231}
232
233// Translate glslang language (stage) to SPIR-V execution model.
234spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
235{
236 switch (stage) {
237 case EShLangVertex: return spv::ExecutionModelVertex;
238 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
239 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
240 case EShLangGeometry: return spv::ExecutionModelGeometry;
241 case EShLangFragment: return spv::ExecutionModelFragment;
242 case EShLangCompute: return spv::ExecutionModelGLCompute;
243 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700244 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600245 return spv::ExecutionModelFragment;
246 }
247}
248
John Kessenich140f3df2015-06-26 16:58:36 -0600249// Translate glslang sampler type to SPIR-V dimensionality.
250spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
251{
252 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700253 case glslang::Esd1D: return spv::Dim1D;
254 case glslang::Esd2D: return spv::Dim2D;
255 case glslang::Esd3D: return spv::Dim3D;
256 case glslang::EsdCube: return spv::DimCube;
257 case glslang::EsdRect: return spv::DimRect;
258 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700259 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600260 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700261 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600262 return spv::Dim2D;
263 }
264}
265
John Kessenichf6640762016-08-01 19:44:00 -0600266// Translate glslang precision to SPIR-V precision decorations.
267spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600268{
John Kessenichf6640762016-08-01 19:44:00 -0600269 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700270 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600271 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600272 default:
273 return spv::NoPrecision;
274 }
275}
276
John Kessenichf6640762016-08-01 19:44:00 -0600277// Translate glslang type to SPIR-V precision decorations.
278spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
279{
280 return TranslatePrecisionDecoration(type.getQualifier().precision);
281}
282
John Kessenich140f3df2015-06-26 16:58:36 -0600283// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600284spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600285{
286 if (type.getBasicType() == glslang::EbtBlock) {
287 switch (type.getQualifier().storage) {
288 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600289 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600290 case glslang::EvqVaryingIn: return spv::DecorationBlock;
291 case glslang::EvqVaryingOut: return spv::DecorationBlock;
292 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700293 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600294 break;
295 }
296 }
297
John Kessenich4016e382016-07-15 11:53:56 -0600298 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600299}
300
Rex Xu1da878f2016-02-21 20:59:01 +0800301// Translate glslang type to SPIR-V memory decorations.
302void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
303{
304 if (qualifier.coherent)
305 memory.push_back(spv::DecorationCoherent);
306 if (qualifier.volatil)
307 memory.push_back(spv::DecorationVolatile);
308 if (qualifier.restrict)
309 memory.push_back(spv::DecorationRestrict);
310 if (qualifier.readonly)
311 memory.push_back(spv::DecorationNonWritable);
312 if (qualifier.writeonly)
313 memory.push_back(spv::DecorationNonReadable);
314}
315
John Kessenich140f3df2015-06-26 16:58:36 -0600316// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700317spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600318{
319 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700320 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600321 case glslang::ElmRowMajor:
322 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700323 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600324 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700325 default:
326 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600327 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600328 }
329 } else {
330 switch (type.getBasicType()) {
331 default:
John Kessenich4016e382016-07-15 11:53:56 -0600332 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600333 break;
334 case glslang::EbtBlock:
335 switch (type.getQualifier().storage) {
336 case glslang::EvqUniform:
337 case glslang::EvqBuffer:
338 switch (type.getQualifier().layoutPacking) {
339 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600340 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
341 default:
John Kessenich4016e382016-07-15 11:53:56 -0600342 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600343 }
344 case glslang::EvqVaryingIn:
345 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700346 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600347 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600348 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700349 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600350 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600351 }
352 }
353 }
354}
355
356// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600357// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700358// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800359spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600360{
Rex Xubbceed72016-05-21 09:40:44 +0800361 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700362 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600363 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800364 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700365 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700366 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600367 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800368#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800369 else if (qualifier.explicitInterp) {
370 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800371 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800372 }
Rex Xu9d93a232016-05-05 12:30:44 +0800373#endif
Rex Xubbceed72016-05-21 09:40:44 +0800374 else
John Kessenich4016e382016-07-15 11:53:56 -0600375 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800376}
377
378// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600379// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800380// should be applied.
381spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
382{
383 if (qualifier.patch)
384 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700385 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600386 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700387 else if (qualifier.sample) {
388 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600389 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700390 } else
John Kessenich4016e382016-07-15 11:53:56 -0600391 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600392}
393
John Kessenich92187592016-02-01 13:45:25 -0700394// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700395spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600396{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700397 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600398 return spv::DecorationInvariant;
399 else
John Kessenich4016e382016-07-15 11:53:56 -0600400 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600401}
402
qining9220dbb2016-05-04 17:34:38 -0400403// If glslang type is noContraction, return SPIR-V NoContraction decoration.
404spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
405{
406 if (qualifier.noContraction)
407 return spv::DecorationNoContraction;
408 else
John Kessenich4016e382016-07-15 11:53:56 -0600409 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400410}
411
David Netoa901ffe2016-06-08 14:11:40 +0100412// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
413// associated capabilities when required. For some built-in variables, a capability
414// is generated only when using the variable in an executable instruction, but not when
415// just declaring a struct member variable with it. This is true for PointSize,
416// ClipDistance, and CullDistance.
417spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600418{
419 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700420 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600421 // Defer adding the capability until the built-in is actually used.
422 if (! memberDeclaration) {
423 switch (glslangIntermediate->getStage()) {
424 case EShLangGeometry:
425 builder.addCapability(spv::CapabilityGeometryPointSize);
426 break;
427 case EShLangTessControl:
428 case EShLangTessEvaluation:
429 builder.addCapability(spv::CapabilityTessellationPointSize);
430 break;
431 default:
432 break;
433 }
John Kessenich92187592016-02-01 13:45:25 -0700434 }
435 return spv::BuiltInPointSize;
436
John Kessenichebb50532016-05-16 19:22:05 -0600437 // These *Distance capabilities logically belong here, but if the member is declared and
438 // then never used, consumers of SPIR-V prefer the capability not be declared.
439 // They are now generated when used, rather than here when declared.
440 // Potentially, the specification should be more clear what the minimum
441 // use needed is to trigger the capability.
442 //
John Kessenich92187592016-02-01 13:45:25 -0700443 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100444 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800445 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700446 return spv::BuiltInClipDistance;
447
448 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100449 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800450 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700451 return spv::BuiltInCullDistance;
452
453 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800454 if (!memberDeclaration) {
455 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800456#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800457 if (glslangIntermediate->getStage() == EShLangVertex ||
458 glslangIntermediate->getStage() == EShLangTessControl ||
459 glslangIntermediate->getStage() == EShLangTessEvaluation) {
460
461 builder.addExtension(spv::E_SPV_NV_viewport_array2);
462 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
463 }
chaoc771d89f2017-01-13 01:10:53 -0800464#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800465 }
John Kessenich92187592016-02-01 13:45:25 -0700466 return spv::BuiltInViewportIndex;
467
John Kessenich5e801132016-02-15 11:09:46 -0700468 case glslang::EbvSampleId:
469 builder.addCapability(spv::CapabilitySampleRateShading);
470 return spv::BuiltInSampleId;
471
472 case glslang::EbvSamplePosition:
473 builder.addCapability(spv::CapabilitySampleRateShading);
474 return spv::BuiltInSamplePosition;
475
476 case glslang::EbvSampleMask:
477 builder.addCapability(spv::CapabilitySampleRateShading);
478 return spv::BuiltInSampleMask;
479
John Kessenich78a45572016-07-08 14:05:15 -0600480 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800481 if (!memberDeclaration) {
482 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800483#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800484 if (glslangIntermediate->getStage() == EShLangVertex ||
485 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800486 glslangIntermediate->getStage() == EShLangTessEvaluation) {
487
chaoc771d89f2017-01-13 01:10:53 -0800488 builder.addExtension(spv::E_SPV_NV_viewport_array2);
489 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
490 }
chaoc771d89f2017-01-13 01:10:53 -0800491#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800492 }
493
John Kessenich78a45572016-07-08 14:05:15 -0600494 return spv::BuiltInLayer;
495
John Kessenich140f3df2015-06-26 16:58:36 -0600496 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600497 case glslang::EbvVertexId: return spv::BuiltInVertexId;
498 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700499 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
500 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800501
John Kessenichda581a22015-10-14 14:10:30 -0600502 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800503 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
504 builder.addCapability(spv::CapabilityDrawParameters);
505 return spv::BuiltInBaseVertex;
506
John Kessenichda581a22015-10-14 14:10:30 -0600507 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800508 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
509 builder.addCapability(spv::CapabilityDrawParameters);
510 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200511
John Kessenichda581a22015-10-14 14:10:30 -0600512 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800513 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
514 builder.addCapability(spv::CapabilityDrawParameters);
515 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200516
517 case glslang::EbvPrimitiveId:
518 if (glslangIntermediate->getStage() == EShLangFragment)
519 builder.addCapability(spv::CapabilityGeometry);
520 return spv::BuiltInPrimitiveId;
521
John Kessenich140f3df2015-06-26 16:58:36 -0600522 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600523 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
524 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
525 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
526 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
527 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
528 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
529 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600530 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
531 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
532 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
533 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
534 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
535 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
536 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
537 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800538
Rex Xu574ab042016-04-14 16:53:07 +0800539 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800540 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800541 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
542 return spv::BuiltInSubgroupSize;
543
Rex Xu574ab042016-04-14 16:53:07 +0800544 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800545 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800546 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
547 return spv::BuiltInSubgroupLocalInvocationId;
548
Rex Xu574ab042016-04-14 16:53:07 +0800549 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800550 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
551 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
552 return spv::BuiltInSubgroupEqMaskKHR;
553
Rex Xu574ab042016-04-14 16:53:07 +0800554 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800555 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
556 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
557 return spv::BuiltInSubgroupGeMaskKHR;
558
Rex Xu574ab042016-04-14 16:53:07 +0800559 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800560 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
561 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
562 return spv::BuiltInSubgroupGtMaskKHR;
563
Rex Xu574ab042016-04-14 16:53:07 +0800564 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800565 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
566 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
567 return spv::BuiltInSubgroupLeMaskKHR;
568
Rex Xu574ab042016-04-14 16:53:07 +0800569 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800570 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
571 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
572 return spv::BuiltInSubgroupLtMaskKHR;
573
Rex Xu9d93a232016-05-05 12:30:44 +0800574#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800575 case glslang::EbvBaryCoordNoPersp:
576 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
577 return spv::BuiltInBaryCoordNoPerspAMD;
578
579 case glslang::EbvBaryCoordNoPerspCentroid:
580 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
581 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
582
583 case glslang::EbvBaryCoordNoPerspSample:
584 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
585 return spv::BuiltInBaryCoordNoPerspSampleAMD;
586
587 case glslang::EbvBaryCoordSmooth:
588 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
589 return spv::BuiltInBaryCoordSmoothAMD;
590
591 case glslang::EbvBaryCoordSmoothCentroid:
592 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
593 return spv::BuiltInBaryCoordSmoothCentroidAMD;
594
595 case glslang::EbvBaryCoordSmoothSample:
596 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
597 return spv::BuiltInBaryCoordSmoothSampleAMD;
598
599 case glslang::EbvBaryCoordPullModel:
600 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
601 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800602#endif
chaoc771d89f2017-01-13 01:10:53 -0800603
John Kessenich6c8aaac2017-02-27 01:20:51 -0700604 case glslang::EbvDeviceIndex:
605 builder.addExtension(spv::E_SPV_KHR_device_group);
606 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700607 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700608
609 case glslang::EbvViewIndex:
610 builder.addExtension(spv::E_SPV_KHR_multiview);
611 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700612 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700613
chaoc771d89f2017-01-13 01:10:53 -0800614#ifdef NV_EXTENSIONS
615 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800616 if (!memberDeclaration) {
617 builder.addExtension(spv::E_SPV_NV_viewport_array2);
618 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
619 }
chaoc771d89f2017-01-13 01:10:53 -0800620 return spv::BuiltInViewportMaskNV;
621 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800622 if (!memberDeclaration) {
623 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
624 builder.addCapability(spv::CapabilityShaderStereoViewNV);
625 }
chaoc771d89f2017-01-13 01:10:53 -0800626 return spv::BuiltInSecondaryPositionNV;
627 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800628 if (!memberDeclaration) {
629 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
630 builder.addCapability(spv::CapabilityShaderStereoViewNV);
631 }
chaoc771d89f2017-01-13 01:10:53 -0800632 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800633 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800634 if (!memberDeclaration) {
635 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
636 builder.addCapability(spv::CapabilityPerViewAttributesNV);
637 }
chaocdf3956c2017-02-14 14:52:34 -0800638 return spv::BuiltInPositionPerViewNV;
639 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800640 if (!memberDeclaration) {
641 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
642 builder.addCapability(spv::CapabilityPerViewAttributesNV);
643 }
chaocdf3956c2017-02-14 14:52:34 -0800644 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800645#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800646 default:
647 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600648 }
649}
650
Rex Xufc618912015-09-09 16:42:49 +0800651// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700652spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800653{
654 assert(type.getBasicType() == glslang::EbtSampler);
655
John Kessenich5d0fa972016-02-15 11:57:00 -0700656 // Check for capabilities
657 switch (type.getQualifier().layoutFormat) {
658 case glslang::ElfRg32f:
659 case glslang::ElfRg16f:
660 case glslang::ElfR11fG11fB10f:
661 case glslang::ElfR16f:
662 case glslang::ElfRgba16:
663 case glslang::ElfRgb10A2:
664 case glslang::ElfRg16:
665 case glslang::ElfRg8:
666 case glslang::ElfR16:
667 case glslang::ElfR8:
668 case glslang::ElfRgba16Snorm:
669 case glslang::ElfRg16Snorm:
670 case glslang::ElfRg8Snorm:
671 case glslang::ElfR16Snorm:
672 case glslang::ElfR8Snorm:
673
674 case glslang::ElfRg32i:
675 case glslang::ElfRg16i:
676 case glslang::ElfRg8i:
677 case glslang::ElfR16i:
678 case glslang::ElfR8i:
679
680 case glslang::ElfRgb10a2ui:
681 case glslang::ElfRg32ui:
682 case glslang::ElfRg16ui:
683 case glslang::ElfRg8ui:
684 case glslang::ElfR16ui:
685 case glslang::ElfR8ui:
686 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
687 break;
688
689 default:
690 break;
691 }
692
693 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800694 switch (type.getQualifier().layoutFormat) {
695 case glslang::ElfNone: return spv::ImageFormatUnknown;
696 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
697 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
698 case glslang::ElfR32f: return spv::ImageFormatR32f;
699 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
700 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
701 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
702 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
703 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
704 case glslang::ElfR16f: return spv::ImageFormatR16f;
705 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
706 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
707 case glslang::ElfRg16: return spv::ImageFormatRg16;
708 case glslang::ElfRg8: return spv::ImageFormatRg8;
709 case glslang::ElfR16: return spv::ImageFormatR16;
710 case glslang::ElfR8: return spv::ImageFormatR8;
711 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
712 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
713 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
714 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
715 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
716 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
717 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
718 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
719 case glslang::ElfR32i: return spv::ImageFormatR32i;
720 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
721 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
722 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
723 case glslang::ElfR16i: return spv::ImageFormatR16i;
724 case glslang::ElfR8i: return spv::ImageFormatR8i;
725 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
726 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
727 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
728 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
729 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
730 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
731 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
732 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
733 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
734 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600735 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800736 }
737}
738
steve-lunargf1709e72017-05-02 20:14:50 -0600739spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
740{
741 switch (loopControl) {
742 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
743 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
744 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
745 // TODO: DependencyInfinite
746 // TODO: DependencyLength
747 default: return spv::LoopControlMaskNone;
748 }
749}
750
John Kessenicha5c5fb62017-05-05 05:09:58 -0600751// Translate glslang type to SPIR-V storage class.
752spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
753{
754 if (type.getQualifier().isPipeInput())
755 return spv::StorageClassInput;
756 else if (type.getQualifier().isPipeOutput())
757 return spv::StorageClassOutput;
758 else if (type.getBasicType() == glslang::EbtAtomicUint)
759 return spv::StorageClassAtomicCounter;
760 else if (type.containsOpaque())
761 return spv::StorageClassUniformConstant;
762 else if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
763 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
764 return spv::StorageClassStorageBuffer;
765 } else if (type.getQualifier().isUniformOrBuffer()) {
766 if (type.getQualifier().layoutPushConstant)
767 return spv::StorageClassPushConstant;
768 if (type.getBasicType() == glslang::EbtBlock)
769 return spv::StorageClassUniform;
770 else
771 return spv::StorageClassUniformConstant;
772 } else {
773 switch (type.getQualifier().storage) {
774 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
775 case glslang::EvqGlobal: return spv::StorageClassPrivate;
776 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
777 case glslang::EvqTemporary: return spv::StorageClassFunction;
778 default:
779 assert(0);
780 return spv::StorageClassFunction;
781 }
782 }
783}
784
qining25262b32016-05-06 17:25:16 -0400785// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700786// descriptor set.
787bool IsDescriptorResource(const glslang::TType& type)
788{
John Kessenichf7497e22016-03-08 21:36:22 -0700789 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700790 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700791 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700792
793 // non block...
794 // basically samplerXXX/subpass/sampler/texture are all included
795 // if they are the global-scope-class, not the function parameter
796 // (or local, if they ever exist) class.
797 if (type.getBasicType() == glslang::EbtSampler)
798 return type.getQualifier().isUniformOrBuffer();
799
800 // None of the above.
801 return false;
802}
803
John Kesseniche0b6cad2015-12-24 10:30:13 -0700804void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
805{
806 if (child.layoutMatrix == glslang::ElmNone)
807 child.layoutMatrix = parent.layoutMatrix;
808
809 if (parent.invariant)
810 child.invariant = true;
811 if (parent.nopersp)
812 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800813#ifdef AMD_EXTENSIONS
814 if (parent.explicitInterp)
815 child.explicitInterp = true;
816#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700817 if (parent.flat)
818 child.flat = true;
819 if (parent.centroid)
820 child.centroid = true;
821 if (parent.patch)
822 child.patch = true;
823 if (parent.sample)
824 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800825 if (parent.coherent)
826 child.coherent = true;
827 if (parent.volatil)
828 child.volatil = true;
829 if (parent.restrict)
830 child.restrict = true;
831 if (parent.readonly)
832 child.readonly = true;
833 if (parent.writeonly)
834 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700835}
836
John Kessenichf2b7f332016-09-01 17:05:23 -0600837bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700838{
John Kessenich7b9fa252016-01-21 18:56:57 -0700839 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600840 // - struct members might inherit from a struct declaration
841 // (note that non-block structs don't explicitly inherit,
842 // only implicitly, meaning no decoration involved)
843 // - affect decorations on the struct members
844 // (note smooth does not, and expecting something like volatile
845 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700846 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600847 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700848}
849
John Kessenich140f3df2015-06-26 16:58:36 -0600850//
851// Implement the TGlslangToSpvTraverser class.
852//
853
Lei Zhang17535f72016-05-04 15:55:59 -0400854TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600855 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
856 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400857 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700858 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600859 glslangIntermediate(glslangIntermediate)
860{
861 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
862
863 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700864 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600865 stdBuiltins = builder.import("GLSL.std.450");
866 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600867 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
868 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600869
870 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600871 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
872 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600873 builder.addSourceExtension(it->c_str());
874
875 // Add the top-level modes for this shader.
876
John Kessenich92187592016-02-01 13:45:25 -0700877 if (glslangIntermediate->getXfbMode()) {
878 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600879 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700880 }
John Kessenich140f3df2015-06-26 16:58:36 -0600881
882 unsigned int mode;
883 switch (glslangIntermediate->getStage()) {
884 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600885 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600886 break;
887
steve-lunarge7412492017-03-23 11:56:07 -0600888 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600889 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600890 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600891
steve-lunarge7412492017-03-23 11:56:07 -0600892 glslang::TLayoutGeometry primitive;
893
894 if (glslangIntermediate->getStage() == EShLangTessControl) {
895 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
896 primitive = glslangIntermediate->getOutputPrimitive();
897 } else {
898 primitive = glslangIntermediate->getInputPrimitive();
899 }
900
901 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700902 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
903 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
904 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600905 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600906 }
John Kessenich4016e382016-07-15 11:53:56 -0600907 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600908 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
909
John Kesseniche6903322015-10-13 16:29:02 -0600910 switch (glslangIntermediate->getVertexSpacing()) {
911 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
912 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
913 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600914 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600915 }
John Kessenich4016e382016-07-15 11:53:56 -0600916 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600917 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
918
919 switch (glslangIntermediate->getVertexOrder()) {
920 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
921 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600922 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600923 }
John Kessenich4016e382016-07-15 11:53:56 -0600924 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600925 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
926
927 if (glslangIntermediate->getPointMode())
928 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600929 break;
930
931 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600932 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600933 switch (glslangIntermediate->getInputPrimitive()) {
934 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
935 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
936 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700937 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600938 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600939 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600940 }
John Kessenich4016e382016-07-15 11:53:56 -0600941 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600942 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600943
John Kessenich140f3df2015-06-26 16:58:36 -0600944 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
945
946 switch (glslangIntermediate->getOutputPrimitive()) {
947 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
948 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
949 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600950 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600951 }
John Kessenich4016e382016-07-15 11:53:56 -0600952 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600953 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
954 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
955 break;
956
957 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600958 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600959 if (glslangIntermediate->getPixelCenterInteger())
960 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600961
John Kessenich140f3df2015-06-26 16:58:36 -0600962 if (glslangIntermediate->getOriginUpperLeft())
963 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600964 else
965 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600966
967 if (glslangIntermediate->getEarlyFragmentTests())
968 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
969
970 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600971 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
972 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600973 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600974 }
John Kessenich4016e382016-07-15 11:53:56 -0600975 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600976 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
977
978 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
979 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600980 break;
981
982 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600983 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600984 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
985 glslangIntermediate->getLocalSize(1),
986 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600987 break;
988
989 default:
990 break;
991 }
John Kessenich140f3df2015-06-26 16:58:36 -0600992}
993
John Kessenichfca82622016-11-26 13:23:20 -0700994// Finish creating SPV, after the traversal is complete.
995void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700996{
John Kessenich517fe7a2016-11-26 13:31:47 -0700997 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700998 builder.setBuildPoint(shaderEntry->getLastBlock());
999 builder.leaveFunction();
1000 }
1001
John Kessenich7ba63412015-12-20 17:37:07 -07001002 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001003 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1004 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001005
qiningda397332016-03-09 19:54:03 -05001006 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001007}
1008
John Kessenichfca82622016-11-26 13:23:20 -07001009// Write the SPV into 'out'.
1010void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001011{
John Kessenichfca82622016-11-26 13:23:20 -07001012 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001013}
1014
1015//
1016// Implement the traversal functions.
1017//
1018// Return true from interior nodes to have the external traversal
1019// continue on to children. Return false if children were
1020// already processed.
1021//
1022
1023//
qining25262b32016-05-06 17:25:16 -04001024// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001025// - uniform/input reads
1026// - output writes
1027// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1028// - something simple that degenerates into the last bullet
1029//
1030void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1031{
qining75d1d802016-04-06 14:42:01 -04001032 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1033 if (symbol->getType().getQualifier().isSpecConstant())
1034 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1035
John Kessenich140f3df2015-06-26 16:58:36 -06001036 // getSymbolId() will set up all the IO decorations on the first call.
1037 // Formal function parameters were mapped during makeFunctions().
1038 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001039
1040 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1041 if (builder.isPointer(id)) {
1042 spv::StorageClass sc = builder.getStorageClass(id);
1043 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1044 iOSet.insert(id);
1045 }
1046
1047 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001048 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001049 // Prepare to generate code for the access
1050
1051 // L-value chains will be computed left to right. We're on the symbol now,
1052 // which is the left-most part of the access chain, so now is "clear" time,
1053 // followed by setting the base.
1054 builder.clearAccessChain();
1055
1056 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001057 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001058 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001059 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001060 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001061 // These are also pure R-values.
1062 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001063 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001064 builder.setAccessChainRValue(id);
1065 else
1066 builder.setAccessChainLValue(id);
1067 }
1068}
1069
1070bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1071{
qining40887662016-04-03 22:20:42 -04001072 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1073 if (node->getType().getQualifier().isSpecConstant())
1074 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1075
John Kessenich140f3df2015-06-26 16:58:36 -06001076 // First, handle special cases
1077 switch (node->getOp()) {
1078 case glslang::EOpAssign:
1079 case glslang::EOpAddAssign:
1080 case glslang::EOpSubAssign:
1081 case glslang::EOpMulAssign:
1082 case glslang::EOpVectorTimesMatrixAssign:
1083 case glslang::EOpVectorTimesScalarAssign:
1084 case glslang::EOpMatrixTimesScalarAssign:
1085 case glslang::EOpMatrixTimesMatrixAssign:
1086 case glslang::EOpDivAssign:
1087 case glslang::EOpModAssign:
1088 case glslang::EOpAndAssign:
1089 case glslang::EOpInclusiveOrAssign:
1090 case glslang::EOpExclusiveOrAssign:
1091 case glslang::EOpLeftShiftAssign:
1092 case glslang::EOpRightShiftAssign:
1093 // A bin-op assign "a += b" means the same thing as "a = a + b"
1094 // where a is evaluated before b. For a simple assignment, GLSL
1095 // says to evaluate the left before the right. So, always, left
1096 // node then right node.
1097 {
1098 // get the left l-value, save it away
1099 builder.clearAccessChain();
1100 node->getLeft()->traverse(this);
1101 spv::Builder::AccessChain lValue = builder.getAccessChain();
1102
1103 // evaluate the right
1104 builder.clearAccessChain();
1105 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001106 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001107
1108 if (node->getOp() != glslang::EOpAssign) {
1109 // the left is also an r-value
1110 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001111 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001112
1113 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001114 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001115 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001116 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1117 node->getType().getBasicType());
1118
1119 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001120 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001121 }
1122
1123 // store the result
1124 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001125 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001126
1127 // assignments are expressions having an rValue after they are evaluated...
1128 builder.clearAccessChain();
1129 builder.setAccessChainRValue(rValue);
1130 }
1131 return false;
1132 case glslang::EOpIndexDirect:
1133 case glslang::EOpIndexDirectStruct:
1134 {
1135 // Get the left part of the access chain.
1136 node->getLeft()->traverse(this);
1137
1138 // Add the next element in the chain
1139
David Netoa901ffe2016-06-08 14:11:40 +01001140 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001141 if (! node->getLeft()->getType().isArray() &&
1142 node->getLeft()->getType().isVector() &&
1143 node->getOp() == glslang::EOpIndexDirect) {
1144 // This is essentially a hard-coded vector swizzle of size 1,
1145 // so short circuit the access-chain stuff with a swizzle.
1146 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001147 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001148 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001149 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001150 int spvIndex = glslangIndex;
1151 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1152 node->getOp() == glslang::EOpIndexDirectStruct)
1153 {
1154 // This may be, e.g., an anonymous block-member selection, which generally need
1155 // index remapping due to hidden members in anonymous blocks.
1156 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1157 assert(remapper.size() > 0);
1158 spvIndex = remapper[glslangIndex];
1159 }
John Kessenichebb50532016-05-16 19:22:05 -06001160
David Netoa901ffe2016-06-08 14:11:40 +01001161 // normal case for indexing array or structure or block
1162 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1163
1164 // Add capabilities here for accessing PointSize and clip/cull distance.
1165 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001166 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001167 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001168 }
1169 }
1170 return false;
1171 case glslang::EOpIndexIndirect:
1172 {
1173 // Structure or array or vector indirection.
1174 // Will use native SPIR-V access-chain for struct and array indirection;
1175 // matrices are arrays of vectors, so will also work for a matrix.
1176 // Will use the access chain's 'component' for variable index into a vector.
1177
1178 // This adapter is building access chains left to right.
1179 // Set up the access chain to the left.
1180 node->getLeft()->traverse(this);
1181
1182 // save it so that computing the right side doesn't trash it
1183 spv::Builder::AccessChain partial = builder.getAccessChain();
1184
1185 // compute the next index in the chain
1186 builder.clearAccessChain();
1187 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001188 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001189
1190 // restore the saved access chain
1191 builder.setAccessChain(partial);
1192
1193 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001194 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001195 else
John Kessenichfa668da2015-09-13 14:46:30 -06001196 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001197 }
1198 return false;
1199 case glslang::EOpVectorSwizzle:
1200 {
1201 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001202 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001203 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001204 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001205 }
1206 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001207 case glslang::EOpMatrixSwizzle:
1208 logger->missingFunctionality("matrix swizzle");
1209 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001210 case glslang::EOpLogicalOr:
1211 case glslang::EOpLogicalAnd:
1212 {
1213
1214 // These may require short circuiting, but can sometimes be done as straight
1215 // binary operations. The right operand must be short circuited if it has
1216 // side effects, and should probably be if it is complex.
1217 if (isTrivial(node->getRight()->getAsTyped()))
1218 break; // handle below as a normal binary operation
1219 // otherwise, we need to do dynamic short circuiting on the right operand
1220 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1221 builder.clearAccessChain();
1222 builder.setAccessChainRValue(result);
1223 }
1224 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001225 default:
1226 break;
1227 }
1228
1229 // Assume generic binary op...
1230
John Kessenich32cfd492016-02-02 12:37:46 -07001231 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001232 builder.clearAccessChain();
1233 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001234 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001235
John Kessenich32cfd492016-02-02 12:37:46 -07001236 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001237 builder.clearAccessChain();
1238 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001239 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001240
John Kessenich32cfd492016-02-02 12:37:46 -07001241 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001242 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001243 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001244 convertGlslangToSpvType(node->getType()), left, right,
1245 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001246
John Kessenich50e57562015-12-21 21:21:11 -07001247 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001248 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001249 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001250 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001251 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001252 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001253 return false;
1254 }
John Kessenich140f3df2015-06-26 16:58:36 -06001255}
1256
1257bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1258{
qining40887662016-04-03 22:20:42 -04001259 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1260 if (node->getType().getQualifier().isSpecConstant())
1261 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1262
John Kessenichfc51d282015-08-19 13:34:18 -06001263 spv::Id result = spv::NoResult;
1264
1265 // try texturing first
1266 result = createImageTextureFunctionCall(node);
1267 if (result != spv::NoResult) {
1268 builder.clearAccessChain();
1269 builder.setAccessChainRValue(result);
1270
1271 return false; // done with this node
1272 }
1273
1274 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001275
1276 if (node->getOp() == glslang::EOpArrayLength) {
1277 // Quite special; won't want to evaluate the operand.
1278
1279 // Normal .length() would have been constant folded by the front-end.
1280 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001281 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001282 assert(node->getOperand()->getType().isRuntimeSizedArray());
1283 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1284 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001285 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1286 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001287
1288 builder.clearAccessChain();
1289 builder.setAccessChainRValue(length);
1290
1291 return false;
1292 }
1293
John Kessenichfc51d282015-08-19 13:34:18 -06001294 // Start by evaluating the operand
1295
John Kessenich8c8505c2016-07-26 12:50:38 -06001296 // Does it need a swizzle inversion? If so, evaluation is inverted;
1297 // operate first on the swizzle base, then apply the swizzle.
1298 spv::Id invertedType = spv::NoType;
1299 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1300 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1301 invertedType = getInvertedSwizzleType(*node->getOperand());
1302
John Kessenich140f3df2015-06-26 16:58:36 -06001303 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001304 if (invertedType != spv::NoType)
1305 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1306 else
1307 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001308
Rex Xufc618912015-09-09 16:42:49 +08001309 spv::Id operand = spv::NoResult;
1310
1311 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1312 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001313 node->getOp() == glslang::EOpAtomicCounter ||
1314 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001315 operand = builder.accessChainGetLValue(); // Special case l-value operands
1316 else
John Kessenich32cfd492016-02-02 12:37:46 -07001317 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001318
John Kessenichf6640762016-08-01 19:44:00 -06001319 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001320 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001321
1322 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001323 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001324 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001325
1326 // if not, then possibly an operation
1327 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001328 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001329
1330 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001331 if (invertedType)
1332 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1333
John Kessenich140f3df2015-06-26 16:58:36 -06001334 builder.clearAccessChain();
1335 builder.setAccessChainRValue(result);
1336
1337 return false; // done with this node
1338 }
1339
1340 // it must be a special case, check...
1341 switch (node->getOp()) {
1342 case glslang::EOpPostIncrement:
1343 case glslang::EOpPostDecrement:
1344 case glslang::EOpPreIncrement:
1345 case glslang::EOpPreDecrement:
1346 {
1347 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001348 spv::Id one = 0;
1349 if (node->getBasicType() == glslang::EbtFloat)
1350 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001351 else if (node->getBasicType() == glslang::EbtDouble)
1352 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001353#ifdef AMD_EXTENSIONS
1354 else if (node->getBasicType() == glslang::EbtFloat16)
1355 one = builder.makeFloat16Constant(1.0F);
1356#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001357 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1358 one = builder.makeInt64Constant(1);
1359 else
1360 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001361 glslang::TOperator op;
1362 if (node->getOp() == glslang::EOpPreIncrement ||
1363 node->getOp() == glslang::EOpPostIncrement)
1364 op = glslang::EOpAdd;
1365 else
1366 op = glslang::EOpSub;
1367
John Kessenichf6640762016-08-01 19:44:00 -06001368 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001369 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001370 convertGlslangToSpvType(node->getType()), operand, one,
1371 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001372 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001373
1374 // The result of operation is always stored, but conditionally the
1375 // consumed result. The consumed result is always an r-value.
1376 builder.accessChainStore(result);
1377 builder.clearAccessChain();
1378 if (node->getOp() == glslang::EOpPreIncrement ||
1379 node->getOp() == glslang::EOpPreDecrement)
1380 builder.setAccessChainRValue(result);
1381 else
1382 builder.setAccessChainRValue(operand);
1383 }
1384
1385 return false;
1386
1387 case glslang::EOpEmitStreamVertex:
1388 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1389 return false;
1390 case glslang::EOpEndStreamPrimitive:
1391 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1392 return false;
1393
1394 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001395 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001396 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001397 }
John Kessenich140f3df2015-06-26 16:58:36 -06001398}
1399
1400bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1401{
qining27e04a02016-04-14 16:40:20 -04001402 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1403 if (node->getType().getQualifier().isSpecConstant())
1404 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1405
John Kessenichfc51d282015-08-19 13:34:18 -06001406 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001407 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1408 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001409
1410 // try texturing
1411 result = createImageTextureFunctionCall(node);
1412 if (result != spv::NoResult) {
1413 builder.clearAccessChain();
1414 builder.setAccessChainRValue(result);
1415
1416 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001417 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001418 // "imageStore" is a special case, which has no result
1419 return false;
1420 }
John Kessenichfc51d282015-08-19 13:34:18 -06001421
John Kessenich140f3df2015-06-26 16:58:36 -06001422 glslang::TOperator binOp = glslang::EOpNull;
1423 bool reduceComparison = true;
1424 bool isMatrix = false;
1425 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001426 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001427
1428 assert(node->getOp());
1429
John Kessenichf6640762016-08-01 19:44:00 -06001430 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001431
1432 switch (node->getOp()) {
1433 case glslang::EOpSequence:
1434 {
1435 if (preVisit)
1436 ++sequenceDepth;
1437 else
1438 --sequenceDepth;
1439
1440 if (sequenceDepth == 1) {
1441 // If this is the parent node of all the functions, we want to see them
1442 // early, so all call points have actual SPIR-V functions to reference.
1443 // In all cases, still let the traverser visit the children for us.
1444 makeFunctions(node->getAsAggregate()->getSequence());
1445
John Kessenich6fccb3c2016-09-19 16:01:41 -06001446 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001447 // anything else gets there, so visit out of order, doing them all now.
1448 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1449
John Kessenich6a60c2f2016-12-08 21:01:59 -07001450 // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
John Kessenich140f3df2015-06-26 16:58:36 -06001451 // so do them manually.
1452 visitFunctions(node->getAsAggregate()->getSequence());
1453
1454 return false;
1455 }
1456
1457 return true;
1458 }
1459 case glslang::EOpLinkerObjects:
1460 {
1461 if (visit == glslang::EvPreVisit)
1462 linkageOnly = true;
1463 else
1464 linkageOnly = false;
1465
1466 return true;
1467 }
1468 case glslang::EOpComma:
1469 {
1470 // processing from left to right naturally leaves the right-most
1471 // lying around in the access chain
1472 glslang::TIntermSequence& glslangOperands = node->getSequence();
1473 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1474 glslangOperands[i]->traverse(this);
1475
1476 return false;
1477 }
1478 case glslang::EOpFunction:
1479 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001480 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001481 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001482 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001483 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001484 } else {
1485 handleFunctionEntry(node);
1486 }
1487 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001488 if (inEntryPoint)
1489 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001490 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001491 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001492 }
1493
1494 return true;
1495 case glslang::EOpParameters:
1496 // Parameters will have been consumed by EOpFunction processing, but not
1497 // the body, so we still visited the function node's children, making this
1498 // child redundant.
1499 return false;
1500 case glslang::EOpFunctionCall:
1501 {
1502 if (node->isUserDefined())
1503 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001504 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07001505 if (result) {
1506 builder.clearAccessChain();
1507 builder.setAccessChainRValue(result);
1508 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001509 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001510
1511 return false;
1512 }
1513 case glslang::EOpConstructMat2x2:
1514 case glslang::EOpConstructMat2x3:
1515 case glslang::EOpConstructMat2x4:
1516 case glslang::EOpConstructMat3x2:
1517 case glslang::EOpConstructMat3x3:
1518 case glslang::EOpConstructMat3x4:
1519 case glslang::EOpConstructMat4x2:
1520 case glslang::EOpConstructMat4x3:
1521 case glslang::EOpConstructMat4x4:
1522 case glslang::EOpConstructDMat2x2:
1523 case glslang::EOpConstructDMat2x3:
1524 case glslang::EOpConstructDMat2x4:
1525 case glslang::EOpConstructDMat3x2:
1526 case glslang::EOpConstructDMat3x3:
1527 case glslang::EOpConstructDMat3x4:
1528 case glslang::EOpConstructDMat4x2:
1529 case glslang::EOpConstructDMat4x3:
1530 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001531#ifdef AMD_EXTENSIONS
1532 case glslang::EOpConstructF16Mat2x2:
1533 case glslang::EOpConstructF16Mat2x3:
1534 case glslang::EOpConstructF16Mat2x4:
1535 case glslang::EOpConstructF16Mat3x2:
1536 case glslang::EOpConstructF16Mat3x3:
1537 case glslang::EOpConstructF16Mat3x4:
1538 case glslang::EOpConstructF16Mat4x2:
1539 case glslang::EOpConstructF16Mat4x3:
1540 case glslang::EOpConstructF16Mat4x4:
1541#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001542 isMatrix = true;
1543 // fall through
1544 case glslang::EOpConstructFloat:
1545 case glslang::EOpConstructVec2:
1546 case glslang::EOpConstructVec3:
1547 case glslang::EOpConstructVec4:
1548 case glslang::EOpConstructDouble:
1549 case glslang::EOpConstructDVec2:
1550 case glslang::EOpConstructDVec3:
1551 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001552#ifdef AMD_EXTENSIONS
1553 case glslang::EOpConstructFloat16:
1554 case glslang::EOpConstructF16Vec2:
1555 case glslang::EOpConstructF16Vec3:
1556 case glslang::EOpConstructF16Vec4:
1557#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001558 case glslang::EOpConstructBool:
1559 case glslang::EOpConstructBVec2:
1560 case glslang::EOpConstructBVec3:
1561 case glslang::EOpConstructBVec4:
1562 case glslang::EOpConstructInt:
1563 case glslang::EOpConstructIVec2:
1564 case glslang::EOpConstructIVec3:
1565 case glslang::EOpConstructIVec4:
1566 case glslang::EOpConstructUint:
1567 case glslang::EOpConstructUVec2:
1568 case glslang::EOpConstructUVec3:
1569 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001570 case glslang::EOpConstructInt64:
1571 case glslang::EOpConstructI64Vec2:
1572 case glslang::EOpConstructI64Vec3:
1573 case glslang::EOpConstructI64Vec4:
1574 case glslang::EOpConstructUint64:
1575 case glslang::EOpConstructU64Vec2:
1576 case glslang::EOpConstructU64Vec3:
1577 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001578 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001579 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001580 {
1581 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001582 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001583 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001584 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001585 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001586 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001587 std::vector<spv::Id> constituents;
1588 for (int c = 0; c < (int)arguments.size(); ++c)
1589 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001590 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001591 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001592 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001593 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001594 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001595
1596 builder.clearAccessChain();
1597 builder.setAccessChainRValue(constructed);
1598
1599 return false;
1600 }
1601
1602 // These six are component-wise compares with component-wise results.
1603 // Forward on to createBinaryOperation(), requesting a vector result.
1604 case glslang::EOpLessThan:
1605 case glslang::EOpGreaterThan:
1606 case glslang::EOpLessThanEqual:
1607 case glslang::EOpGreaterThanEqual:
1608 case glslang::EOpVectorEqual:
1609 case glslang::EOpVectorNotEqual:
1610 {
1611 // Map the operation to a binary
1612 binOp = node->getOp();
1613 reduceComparison = false;
1614 switch (node->getOp()) {
1615 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1616 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1617 default: binOp = node->getOp(); break;
1618 }
1619
1620 break;
1621 }
1622 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001623 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001624 binOp = glslang::EOpMul;
1625 break;
1626 case glslang::EOpOuterProduct:
1627 // two vectors multiplied to make a matrix
1628 binOp = glslang::EOpOuterProduct;
1629 break;
1630 case glslang::EOpDot:
1631 {
qining25262b32016-05-06 17:25:16 -04001632 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001633 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001634 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001635 binOp = glslang::EOpMul;
1636 break;
1637 }
1638 case glslang::EOpMod:
1639 // when an aggregate, this is the floating-point mod built-in function,
1640 // which can be emitted by the one in createBinaryOperation()
1641 binOp = glslang::EOpMod;
1642 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001643 case glslang::EOpEmitVertex:
1644 case glslang::EOpEndPrimitive:
1645 case glslang::EOpBarrier:
1646 case glslang::EOpMemoryBarrier:
1647 case glslang::EOpMemoryBarrierAtomicCounter:
1648 case glslang::EOpMemoryBarrierBuffer:
1649 case glslang::EOpMemoryBarrierImage:
1650 case glslang::EOpMemoryBarrierShared:
1651 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001652 case glslang::EOpAllMemoryBarrierWithGroupSync:
1653 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1654 case glslang::EOpWorkgroupMemoryBarrier:
1655 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001656 noReturnValue = true;
1657 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1658 break;
1659
John Kessenich426394d2015-07-23 10:22:48 -06001660 case glslang::EOpAtomicAdd:
1661 case glslang::EOpAtomicMin:
1662 case glslang::EOpAtomicMax:
1663 case glslang::EOpAtomicAnd:
1664 case glslang::EOpAtomicOr:
1665 case glslang::EOpAtomicXor:
1666 case glslang::EOpAtomicExchange:
1667 case glslang::EOpAtomicCompSwap:
1668 atomic = true;
1669 break;
1670
John Kessenich140f3df2015-06-26 16:58:36 -06001671 default:
1672 break;
1673 }
1674
1675 //
1676 // See if it maps to a regular operation.
1677 //
John Kessenich140f3df2015-06-26 16:58:36 -06001678 if (binOp != glslang::EOpNull) {
1679 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1680 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1681 assert(left && right);
1682
1683 builder.clearAccessChain();
1684 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001685 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001686
1687 builder.clearAccessChain();
1688 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001689 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001690
qining25262b32016-05-06 17:25:16 -04001691 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001692 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001693 left->getType().getBasicType(), reduceComparison);
1694
1695 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001696 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001697 builder.clearAccessChain();
1698 builder.setAccessChainRValue(result);
1699
1700 return false;
1701 }
1702
John Kessenich426394d2015-07-23 10:22:48 -06001703 //
1704 // Create the list of operands.
1705 //
John Kessenich140f3df2015-06-26 16:58:36 -06001706 glslang::TIntermSequence& glslangOperands = node->getSequence();
1707 std::vector<spv::Id> operands;
1708 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001709 // special case l-value operands; there are just a few
1710 bool lvalue = false;
1711 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001712 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001713 case glslang::EOpModf:
1714 if (arg == 1)
1715 lvalue = true;
1716 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001717 case glslang::EOpInterpolateAtSample:
1718 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001719#ifdef AMD_EXTENSIONS
1720 case glslang::EOpInterpolateAtVertex:
1721#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001722 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001723 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001724
1725 // Does it need a swizzle inversion? If so, evaluation is inverted;
1726 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001727 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001728 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1729 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1730 }
Rex Xu7a26c172015-12-08 17:12:09 +08001731 break;
Rex Xud4782c12015-09-06 16:30:11 +08001732 case glslang::EOpAtomicAdd:
1733 case glslang::EOpAtomicMin:
1734 case glslang::EOpAtomicMax:
1735 case glslang::EOpAtomicAnd:
1736 case glslang::EOpAtomicOr:
1737 case glslang::EOpAtomicXor:
1738 case glslang::EOpAtomicExchange:
1739 case glslang::EOpAtomicCompSwap:
1740 if (arg == 0)
1741 lvalue = true;
1742 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001743 case glslang::EOpAddCarry:
1744 case glslang::EOpSubBorrow:
1745 if (arg == 2)
1746 lvalue = true;
1747 break;
1748 case glslang::EOpUMulExtended:
1749 case glslang::EOpIMulExtended:
1750 if (arg >= 2)
1751 lvalue = true;
1752 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001753 default:
1754 break;
1755 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001756 builder.clearAccessChain();
1757 if (invertedType != spv::NoType && arg == 0)
1758 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1759 else
1760 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001761 if (lvalue)
1762 operands.push_back(builder.accessChainGetLValue());
1763 else
John Kessenich32cfd492016-02-02 12:37:46 -07001764 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001765 }
John Kessenich426394d2015-07-23 10:22:48 -06001766
1767 if (atomic) {
1768 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001769 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001770 } else {
1771 // Pass through to generic operations.
1772 switch (glslangOperands.size()) {
1773 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001774 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001775 break;
1776 case 1:
qining25262b32016-05-06 17:25:16 -04001777 result = createUnaryOperation(
1778 node->getOp(), precision,
1779 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001780 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001781 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001782 break;
1783 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001784 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001785 break;
1786 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001787 if (invertedType)
1788 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001789 }
1790
1791 if (noReturnValue)
1792 return false;
1793
1794 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001795 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001796 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001797 } else {
1798 builder.clearAccessChain();
1799 builder.setAccessChainRValue(result);
1800 return false;
1801 }
1802}
1803
John Kessenich433e9ff2017-01-26 20:31:11 -07001804// This path handles both if-then-else and ?:
1805// The if-then-else has a node type of void, while
1806// ?: has either a void or a non-void node type
1807//
1808// Leaving the result, when not void:
1809// GLSL only has r-values as the result of a :?, but
1810// if we have an l-value, that can be more efficient if it will
1811// become the base of a complex r-value expression, because the
1812// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001813bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1814{
John Kessenich433e9ff2017-01-26 20:31:11 -07001815 // See if it simple and safe to generate OpSelect instead of using control flow.
1816 // Crucially, side effects must be avoided, and there are performance trade-offs.
1817 // Return true if good idea (and safe) for OpSelect, false otherwise.
1818 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001819 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1820 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001821 return false;
1822
1823 if (node->getTrueBlock() == nullptr ||
1824 node->getFalseBlock() == nullptr)
1825 return false;
1826
1827 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1828 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1829
1830 // return true if a single operand to ? : is okay for OpSelect
1831 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001832 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001833 };
1834
1835 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1836 operandOkay(node->getFalseBlock()->getAsTyped());
1837 };
1838
1839 // Emit OpSelect for this selection.
1840 const auto handleAsOpSelect = [&]() {
1841 node->getCondition()->traverse(this);
1842 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1843 node->getTrueBlock()->traverse(this);
1844 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1845 node->getFalseBlock()->traverse(this);
1846 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1847
John Kesseniche434ad92017-03-30 10:09:28 -06001848 // smear condition to vector, if necessary (AST is always scalar)
1849 if (builder.isVector(trueValue))
1850 condition = builder.smearScalar(spv::NoPrecision, condition,
1851 builder.makeVectorType(builder.makeBoolType(),
1852 builder.getNumComponents(trueValue)));
1853
1854 spv::Id select = builder.createTriOp(spv::OpSelect,
1855 convertGlslangToSpvType(node->getType()), condition,
1856 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001857 builder.clearAccessChain();
1858 builder.setAccessChainRValue(select);
1859 };
1860
1861 // Try for OpSelect
1862
1863 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001864 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1865 if (node->getType().getQualifier().isSpecConstant())
1866 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1867
John Kessenich433e9ff2017-01-26 20:31:11 -07001868 handleAsOpSelect();
1869 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001870 }
1871
John Kessenich433e9ff2017-01-26 20:31:11 -07001872 // Instead, emit control flow...
1873
1874 // Don't handle results as temporaries, because there will be two names
1875 // and better to leave SSA to later passes.
1876 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1877 ? spv::NoResult
1878 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1879
John Kessenich140f3df2015-06-26 16:58:36 -06001880 // emit the condition before doing anything with selection
1881 node->getCondition()->traverse(this);
1882
1883 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001884 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001885
John Kessenich433e9ff2017-01-26 20:31:11 -07001886 // emit the "then" statement
1887 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001888 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001889 if (result != spv::NoResult)
1890 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001891 }
1892
John Kessenich433e9ff2017-01-26 20:31:11 -07001893 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001894 ifBuilder.makeBeginElse();
1895 // emit the "else" statement
1896 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001897 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001898 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001899 }
1900
John Kessenich433e9ff2017-01-26 20:31:11 -07001901 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001902 ifBuilder.makeEndIf();
1903
John Kessenich433e9ff2017-01-26 20:31:11 -07001904 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001905 // GLSL only has r-values as the result of a :?, but
1906 // if we have an l-value, that can be more efficient if it will
1907 // become the base of a complex r-value expression, because the
1908 // next layer copies r-values into memory to use the access-chain mechanism
1909 builder.clearAccessChain();
1910 builder.setAccessChainLValue(result);
1911 }
1912
1913 return false;
1914}
1915
1916bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1917{
1918 // emit and get the condition before doing anything with switch
1919 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001920 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001921
1922 // browse the children to sort out code segments
1923 int defaultSegment = -1;
1924 std::vector<TIntermNode*> codeSegments;
1925 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1926 std::vector<int> caseValues;
1927 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1928 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1929 TIntermNode* child = *c;
1930 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001931 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001932 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001933 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001934 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1935 } else
1936 codeSegments.push_back(child);
1937 }
1938
qining25262b32016-05-06 17:25:16 -04001939 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001940 // statements between the last case and the end of the switch statement
1941 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1942 (int)codeSegments.size() == defaultSegment)
1943 codeSegments.push_back(nullptr);
1944
1945 // make the switch statement
1946 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001947 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001948
1949 // emit all the code in the segments
1950 breakForLoop.push(false);
1951 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1952 builder.nextSwitchSegment(segmentBlocks, s);
1953 if (codeSegments[s])
1954 codeSegments[s]->traverse(this);
1955 else
1956 builder.addSwitchBreak();
1957 }
1958 breakForLoop.pop();
1959
1960 builder.endSwitch(segmentBlocks);
1961
1962 return false;
1963}
1964
1965void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1966{
1967 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001968 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001969
1970 builder.clearAccessChain();
1971 builder.setAccessChainRValue(constant);
1972}
1973
1974bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1975{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001976 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001977 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06001978
1979 // Loop control:
1980 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
1981
1982 // TODO: dependency length
1983
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001984 // Spec requires back edges to target header blocks, and every header block
1985 // must dominate its merge block. Make a header block first to ensure these
1986 // conditions are met. By definition, it will contain OpLoopMerge, followed
1987 // by a block-ending branch. But we don't want to put any other body/test
1988 // instructions in it, since the body/test may have arbitrary instructions,
1989 // including merges of its own.
1990 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06001991 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001992 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001993 spv::Block& test = builder.makeNewBlock();
1994 builder.createBranch(&test);
1995
1996 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001997 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001998 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001999 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002000 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2001
2002 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002003 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002004 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002005 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002006 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002007 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002008
2009 builder.setBuildPoint(&blocks.continue_target);
2010 if (node->getTerminal())
2011 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002012 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002013 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002014 builder.createBranch(&blocks.body);
2015
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002016 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002017 builder.setBuildPoint(&blocks.body);
2018 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002019 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002020 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002021 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002022
2023 builder.setBuildPoint(&blocks.continue_target);
2024 if (node->getTerminal())
2025 node->getTerminal()->traverse(this);
2026 if (node->getTest()) {
2027 node->getTest()->traverse(this);
2028 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002029 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002030 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002031 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002032 // TODO: unless there was a break/return/discard instruction
2033 // somewhere in the body, this is an infinite loop, so we should
2034 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002035 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002036 }
John Kessenich140f3df2015-06-26 16:58:36 -06002037 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002038 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002039 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002040 return false;
2041}
2042
2043bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2044{
2045 if (node->getExpression())
2046 node->getExpression()->traverse(this);
2047
2048 switch (node->getFlowOp()) {
2049 case glslang::EOpKill:
2050 builder.makeDiscard();
2051 break;
2052 case glslang::EOpBreak:
2053 if (breakForLoop.top())
2054 builder.createLoopExit();
2055 else
2056 builder.addSwitchBreak();
2057 break;
2058 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002059 builder.createLoopContinue();
2060 break;
2061 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002062 if (node->getExpression()) {
2063 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2064 spv::Id returnId = accessChainLoad(glslangReturnType);
2065 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2066 builder.clearAccessChain();
2067 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2068 builder.setAccessChainLValue(copyId);
2069 multiTypeStore(glslangReturnType, returnId);
2070 returnId = builder.createLoad(copyId);
2071 }
2072 builder.makeReturn(false, returnId);
2073 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002074 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002075
2076 builder.clearAccessChain();
2077 break;
2078
2079 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002080 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002081 break;
2082 }
2083
2084 return false;
2085}
2086
2087spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2088{
qining25262b32016-05-06 17:25:16 -04002089 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002090 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002091 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002092 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002093 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002094 }
2095
2096 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002097 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002098 spv::Id spvType = convertGlslangToSpvType(node->getType());
2099
Rex Xuf89ad982017-04-07 23:22:33 +08002100#ifdef AMD_EXTENSIONS
2101 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16);
2102 if (contains16BitType) {
2103 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2104 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2105 builder.addCapability(spv::CapabilityStorageInputOutput16);
2106 } else if (storageClass == spv::StorageClassPushConstant) {
2107 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2108 builder.addCapability(spv::CapabilityStoragePushConstant16);
2109 } else if (storageClass == spv::StorageClassUniform) {
2110 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2111 builder.addCapability(spv::CapabilityStorageUniform16);
2112 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2113 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2114 }
2115 }
2116#endif
2117
John Kessenich140f3df2015-06-26 16:58:36 -06002118 const char* name = node->getName().c_str();
2119 if (glslang::IsAnonymous(name))
2120 name = "";
2121
2122 return builder.createVariable(storageClass, spvType, name);
2123}
2124
2125// Return type Id of the sampled type.
2126spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2127{
2128 switch (sampler.type) {
2129 case glslang::EbtFloat: return builder.makeFloatType(32);
2130 case glslang::EbtInt: return builder.makeIntType(32);
2131 case glslang::EbtUint: return builder.makeUintType(32);
2132 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002133 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002134 return builder.makeFloatType(32);
2135 }
2136}
2137
John Kessenich8c8505c2016-07-26 12:50:38 -06002138// If node is a swizzle operation, return the type that should be used if
2139// the swizzle base is first consumed by another operation, before the swizzle
2140// is applied.
2141spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2142{
John Kessenichecba76f2017-01-06 00:34:48 -07002143 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002144 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2145 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2146 else
2147 return spv::NoType;
2148}
2149
2150// When inverting a swizzle with a parent op, this function
2151// will apply the swizzle operation to a completed parent operation.
2152spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2153{
2154 std::vector<unsigned> swizzle;
2155 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2156 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2157}
2158
John Kessenich8c8505c2016-07-26 12:50:38 -06002159// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2160void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2161{
2162 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2163 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2164 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2165}
2166
John Kessenich3ac051e2015-12-20 11:29:16 -07002167// Convert from a glslang type to an SPV type, by calling into a
2168// recursive version of this function. This establishes the inherited
2169// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002170spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2171{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002172 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002173}
2174
2175// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002176// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002177// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002178spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002179{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002180 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002181
2182 switch (type.getBasicType()) {
2183 case glslang::EbtVoid:
2184 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002185 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002186 break;
2187 case glslang::EbtFloat:
2188 spvType = builder.makeFloatType(32);
2189 break;
2190 case glslang::EbtDouble:
2191 spvType = builder.makeFloatType(64);
2192 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002193#ifdef AMD_EXTENSIONS
2194 case glslang::EbtFloat16:
2195 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002196 spvType = builder.makeFloatType(16);
2197 break;
2198#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002199 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002200 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2201 // a 32-bit int where non-0 means true.
2202 if (explicitLayout != glslang::ElpNone)
2203 spvType = builder.makeUintType(32);
2204 else
2205 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002206 break;
2207 case glslang::EbtInt:
2208 spvType = builder.makeIntType(32);
2209 break;
2210 case glslang::EbtUint:
2211 spvType = builder.makeUintType(32);
2212 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002213 case glslang::EbtInt64:
2214 builder.addCapability(spv::CapabilityInt64);
2215 spvType = builder.makeIntType(64);
2216 break;
2217 case glslang::EbtUint64:
2218 builder.addCapability(spv::CapabilityInt64);
2219 spvType = builder.makeUintType(64);
2220 break;
John Kessenich426394d2015-07-23 10:22:48 -06002221 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002222 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002223 spvType = builder.makeUintType(32);
2224 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002225 case glslang::EbtSampler:
2226 {
2227 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002228 if (sampler.sampler) {
2229 // pure sampler
2230 spvType = builder.makeSamplerType();
2231 } else {
2232 // an image is present, make its type
2233 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2234 sampler.image ? 2 : 1, TranslateImageFormat(type));
2235 if (sampler.combined) {
2236 // already has both image and sampler, make the combined type
2237 spvType = builder.makeSampledImageType(spvType);
2238 }
John Kessenich55e7d112015-11-15 21:33:39 -07002239 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002240 }
John Kessenich140f3df2015-06-26 16:58:36 -06002241 break;
2242 case glslang::EbtStruct:
2243 case glslang::EbtBlock:
2244 {
2245 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002246 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002247
2248 // Try to share structs for different layouts, but not yet for other
2249 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002250 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002251 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002252 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002253 break;
2254
2255 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002256 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002257 memberRemapper[glslangMembers].resize(glslangMembers->size());
2258 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002259 }
2260 break;
2261 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002262 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002263 break;
2264 }
2265
2266 if (type.isMatrix())
2267 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2268 else {
2269 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2270 if (type.getVectorSize() > 1)
2271 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2272 }
2273
2274 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002275 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2276
John Kessenichc9a80832015-09-12 12:17:44 -06002277 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002278 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002279 // We need to decorate array strides for types needing explicit layout, except blocks.
2280 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002281 // Use a dummy glslang type for querying internal strides of
2282 // arrays of arrays, but using just a one-dimensional array.
2283 glslang::TType simpleArrayType(type, 0); // deference type of the array
2284 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2285 simpleArrayType.getArraySizes().dereference();
2286
2287 // Will compute the higher-order strides here, rather than making a whole
2288 // pile of types and doing repetitive recursion on their contents.
2289 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2290 }
John Kessenichf8842e52016-01-04 19:22:56 -07002291
2292 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002293 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002294 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002295 if (stride > 0)
2296 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002297 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002298 }
2299 } else {
2300 // single-dimensional array, and don't yet have stride
2301
John Kessenichf8842e52016-01-04 19:22:56 -07002302 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002303 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2304 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002305 }
John Kessenich31ed4832015-09-09 17:51:38 -06002306
John Kessenichc9a80832015-09-12 12:17:44 -06002307 // Do the outer dimension, which might not be known for a runtime-sized array
2308 if (type.isRuntimeSizedArray()) {
2309 spvType = builder.makeRuntimeArray(spvType);
2310 } else {
2311 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002312 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002313 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002314 if (stride > 0)
2315 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002316 }
2317
2318 return spvType;
2319}
2320
John Kessenich0e737842017-03-24 18:38:16 -06002321// TODO: this functionality should exist at a higher level, in creating the AST
2322//
2323// Identify interface members that don't have their required extension turned on.
2324//
2325bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2326{
2327 auto& extensions = glslangIntermediate->getRequestedExtensions();
2328
Rex Xubcf291a2017-03-29 23:01:36 +08002329 if (member.getFieldName() == "gl_ViewportMask" &&
2330 extensions.find("GL_NV_viewport_array2") == extensions.end())
2331 return true;
2332 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2333 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2334 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002335 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2336 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2337 return true;
2338 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2339 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2340 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002341 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2342 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2343 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002344
2345 return false;
2346};
2347
John Kessenich6090df02016-06-30 21:18:02 -06002348// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2349// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2350// Mutually recursive with convertGlslangToSpvType().
2351spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2352 const glslang::TTypeList* glslangMembers,
2353 glslang::TLayoutPacking explicitLayout,
2354 const glslang::TQualifier& qualifier)
2355{
2356 // Create a vector of struct types for SPIR-V to consume
2357 std::vector<spv::Id> spvMembers;
2358 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2359 int locationOffset = 0; // for use across struct members, when they are called recursively
2360 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2361 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2362 if (glslangMember.hiddenMember()) {
2363 ++memberDelta;
2364 if (type.getBasicType() == glslang::EbtBlock)
2365 memberRemapper[glslangMembers][i] = -1;
2366 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002367 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002368 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002369 if (filterMember(glslangMember))
2370 continue;
2371 }
John Kessenich6090df02016-06-30 21:18:02 -06002372 // modify just this child's view of the qualifier
2373 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2374 InheritQualifiers(memberQualifier, qualifier);
2375
2376 // manually inherit location; it's more complex
2377 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2378 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2379 if (qualifier.hasLocation())
2380 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2381
2382 // recurse
2383 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2384 }
2385 }
2386
2387 // Make the SPIR-V type
2388 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002389 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002390 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2391
2392 // Decorate it
2393 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2394
2395 return spvType;
2396}
2397
2398void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2399 const glslang::TTypeList* glslangMembers,
2400 glslang::TLayoutPacking explicitLayout,
2401 const glslang::TQualifier& qualifier,
2402 spv::Id spvType)
2403{
2404 // Name and decorate the non-hidden members
2405 int offset = -1;
2406 int locationOffset = 0; // for use within the members of this struct
2407 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2408 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2409 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002410 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002411 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002412 if (filterMember(glslangMember))
2413 continue;
2414 }
John Kessenich6090df02016-06-30 21:18:02 -06002415
2416 // modify just this child's view of the qualifier
2417 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2418 InheritQualifiers(memberQualifier, qualifier);
2419
2420 // using -1 above to indicate a hidden member
2421 if (member >= 0) {
2422 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2423 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2424 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2425 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002426 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2427 type.getQualifier().storage == glslang::EvqVaryingOut) {
2428 if (type.getBasicType() == glslang::EbtBlock ||
2429 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002430 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2431 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2432 }
2433 }
2434 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2435
2436 if (qualifier.storage == glslang::EvqBuffer) {
2437 std::vector<spv::Decoration> memory;
2438 TranslateMemoryDecoration(memberQualifier, memory);
2439 for (unsigned int i = 0; i < memory.size(); ++i)
2440 addMemberDecoration(spvType, member, memory[i]);
2441 }
2442
John Kessenich2f47bc92016-06-30 21:47:35 -06002443 // Compute location decoration; tricky based on whether inheritance is at play and
2444 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002445 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2446 // probably move to the linker stage of the front end proper, and just have the
2447 // answer sitting already distributed throughout the individual member locations.
2448 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002449 // Ignore member locations if the container is an array, as that's
2450 // ill-specified and decisions have been made to not allow this anyway.
2451 // The object itself must have a location, and that comes out from decorating the object,
2452 // not the type (this code decorates types).
2453 if (! type.isArray()) {
2454 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2455 // struct members should not have explicit locations
2456 assert(type.getBasicType() != glslang::EbtStruct);
2457 location = memberQualifier.layoutLocation;
2458 } else if (type.getBasicType() != glslang::EbtBlock) {
2459 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2460 // The members, and their nested types, must not themselves have Location decorations.
2461 } else if (qualifier.hasLocation()) // inheritance
2462 location = qualifier.layoutLocation + locationOffset;
2463 }
John Kessenich6090df02016-06-30 21:18:02 -06002464 if (location >= 0)
2465 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2466
John Kessenich2f47bc92016-06-30 21:47:35 -06002467 if (qualifier.hasLocation()) // track for upcoming inheritance
2468 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2469
John Kessenich6090df02016-06-30 21:18:02 -06002470 // component, XFB, others
2471 if (glslangMember.getQualifier().hasComponent())
2472 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2473 if (glslangMember.getQualifier().hasXfbOffset())
2474 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2475 else if (explicitLayout != glslang::ElpNone) {
2476 // figure out what to do with offset, which is accumulating
2477 int nextOffset;
2478 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2479 if (offset >= 0)
2480 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2481 offset = nextOffset;
2482 }
2483
2484 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2485 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2486
2487 // built-in variable decorations
2488 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002489 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002490 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002491
2492#ifdef NV_EXTENSIONS
2493 if (builtIn == spv::BuiltInLayer) {
2494 // SPV_NV_viewport_array2 extension
2495 if (glslangMember.getQualifier().layoutViewportRelative){
2496 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2497 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2498 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2499 }
2500 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2501 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2502 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2503 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2504 }
2505 }
chaocdf3956c2017-02-14 14:52:34 -08002506 if (glslangMember.getQualifier().layoutPassthrough) {
2507 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2508 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2509 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2510 }
chaoc771d89f2017-01-13 01:10:53 -08002511#endif
John Kessenich6090df02016-06-30 21:18:02 -06002512 }
2513 }
2514
2515 // Decorate the structure
2516 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002517 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002518 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2519 builder.addCapability(spv::CapabilityGeometryStreams);
2520 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2521 }
2522 if (glslangIntermediate->getXfbMode()) {
2523 builder.addCapability(spv::CapabilityTransformFeedback);
2524 if (type.getQualifier().hasXfbStride())
2525 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2526 if (type.getQualifier().hasXfbBuffer())
2527 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2528 }
2529}
2530
John Kessenich6c292d32016-02-15 20:58:50 -07002531// Turn the expression forming the array size into an id.
2532// This is not quite trivial, because of specialization constants.
2533// Sometimes, a raw constant is turned into an Id, and sometimes
2534// a specialization constant expression is.
2535spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2536{
2537 // First, see if this is sized with a node, meaning a specialization constant:
2538 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2539 if (specNode != nullptr) {
2540 builder.clearAccessChain();
2541 specNode->traverse(this);
2542 return accessChainLoad(specNode->getAsTyped()->getType());
2543 }
qining25262b32016-05-06 17:25:16 -04002544
John Kessenich6c292d32016-02-15 20:58:50 -07002545 // Otherwise, need a compile-time (front end) size, get it:
2546 int size = arraySizes.getDimSize(dim);
2547 assert(size > 0);
2548 return builder.makeUintConstant(size);
2549}
2550
John Kessenich103bef92016-02-08 21:38:15 -07002551// Wrap the builder's accessChainLoad to:
2552// - localize handling of RelaxedPrecision
2553// - use the SPIR-V inferred type instead of another conversion of the glslang type
2554// (avoids unnecessary work and possible type punning for structures)
2555// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002556spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2557{
John Kessenich103bef92016-02-08 21:38:15 -07002558 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2559 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2560
2561 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002562 if (type.getBasicType() == glslang::EbtBool) {
2563 if (builder.isScalarType(nominalTypeId)) {
2564 // Conversion for bool
2565 spv::Id boolType = builder.makeBoolType();
2566 if (nominalTypeId != boolType)
2567 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2568 } else if (builder.isVectorType(nominalTypeId)) {
2569 // Conversion for bvec
2570 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2571 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2572 if (nominalTypeId != bvecType)
2573 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2574 }
2575 }
John Kessenich103bef92016-02-08 21:38:15 -07002576
2577 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002578}
2579
Rex Xu27253232016-02-23 17:51:09 +08002580// Wrap the builder's accessChainStore to:
2581// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002582//
2583// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002584void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2585{
2586 // Need to convert to abstract types when necessary
2587 if (type.getBasicType() == glslang::EbtBool) {
2588 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2589
2590 if (builder.isScalarType(nominalTypeId)) {
2591 // Conversion for bool
2592 spv::Id boolType = builder.makeBoolType();
John Kessenich80f92a12017-05-19 23:00:13 -06002593 if (nominalTypeId != boolType)
2594 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, builder.makeUintConstant(1),
2595 builder.makeUintConstant(0));
2596 else if (builder.getTypeId(rvalue) != boolType)
2597 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002598 } else if (builder.isVectorType(nominalTypeId)) {
2599 // Conversion for bvec
2600 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2601 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenich80f92a12017-05-19 23:00:13 -06002602 if (nominalTypeId != bvecType)
2603 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue,
2604 makeSmearedConstant(builder.makeUintConstant(1), vecSize),
2605 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2606 else if (builder.getTypeId(rvalue) != bvecType)
2607 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2608 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002609 }
2610 }
2611
2612 builder.accessChainStore(rvalue);
2613}
2614
John Kessenich4bf71552016-09-02 11:20:21 -06002615// For storing when types match at the glslang level, but not might match at the
2616// SPIR-V level.
2617//
2618// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002619// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002620// as in a member-decorated way.
2621//
2622// NOTE: This function can handle any store request; if it's not special it
2623// simplifies to a simple OpStore.
2624//
2625// Implicitly uses the existing builder.accessChain as the storage target.
2626void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2627{
John Kessenichb3e24e42016-09-11 12:33:43 -06002628 // we only do the complex path here if it's an aggregate
2629 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002630 accessChainStore(type, rValue);
2631 return;
2632 }
2633
John Kessenichb3e24e42016-09-11 12:33:43 -06002634 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002635 spv::Id rType = builder.getTypeId(rValue);
2636 spv::Id lValue = builder.accessChainGetLValue();
2637 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2638 if (lType == rType) {
2639 accessChainStore(type, rValue);
2640 return;
2641 }
2642
John Kessenichb3e24e42016-09-11 12:33:43 -06002643 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002644 // where the two types were the same type in GLSL. This requires member
2645 // by member copy, recursively.
2646
John Kessenichb3e24e42016-09-11 12:33:43 -06002647 // If an array, copy element by element.
2648 if (type.isArray()) {
2649 glslang::TType glslangElementType(type, 0);
2650 spv::Id elementRType = builder.getContainedTypeId(rType);
2651 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2652 // get the source member
2653 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002654
John Kessenichb3e24e42016-09-11 12:33:43 -06002655 // set up the target storage
2656 builder.clearAccessChain();
2657 builder.setAccessChainLValue(lValue);
2658 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002659
John Kessenichb3e24e42016-09-11 12:33:43 -06002660 // store the member
2661 multiTypeStore(glslangElementType, elementRValue);
2662 }
2663 } else {
2664 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002665
John Kessenichb3e24e42016-09-11 12:33:43 -06002666 // loop over structure members
2667 const glslang::TTypeList& members = *type.getStruct();
2668 for (int m = 0; m < (int)members.size(); ++m) {
2669 const glslang::TType& glslangMemberType = *members[m].type;
2670
2671 // get the source member
2672 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2673 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2674
2675 // set up the target storage
2676 builder.clearAccessChain();
2677 builder.setAccessChainLValue(lValue);
2678 builder.accessChainPush(builder.makeIntConstant(m));
2679
2680 // store the member
2681 multiTypeStore(glslangMemberType, memberRValue);
2682 }
John Kessenich4bf71552016-09-02 11:20:21 -06002683 }
2684}
2685
John Kessenichf85e8062015-12-19 13:57:10 -07002686// Decide whether or not this type should be
2687// decorated with offsets and strides, and if so
2688// whether std140 or std430 rules should be applied.
2689glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002690{
John Kessenichf85e8062015-12-19 13:57:10 -07002691 // has to be a block
2692 if (type.getBasicType() != glslang::EbtBlock)
2693 return glslang::ElpNone;
2694
2695 // has to be a uniform or buffer block
2696 if (type.getQualifier().storage != glslang::EvqUniform &&
2697 type.getQualifier().storage != glslang::EvqBuffer)
2698 return glslang::ElpNone;
2699
2700 // return the layout to use
2701 switch (type.getQualifier().layoutPacking) {
2702 case glslang::ElpStd140:
2703 case glslang::ElpStd430:
2704 return type.getQualifier().layoutPacking;
2705 default:
2706 return glslang::ElpNone;
2707 }
John Kessenich31ed4832015-09-09 17:51:38 -06002708}
2709
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002710// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002711int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002712{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002713 int size;
John Kessenich49987892015-12-29 17:11:44 -07002714 int stride;
2715 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002716
2717 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002718}
2719
John Kessenich49987892015-12-29 17:11:44 -07002720// 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 -07002721// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002722int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002723{
John Kessenich49987892015-12-29 17:11:44 -07002724 glslang::TType elementType;
2725 elementType.shallowCopy(matrixType);
2726 elementType.clearArraySizes();
2727
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002728 int size;
John Kessenich49987892015-12-29 17:11:44 -07002729 int stride;
2730 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2731
2732 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002733}
2734
John Kessenich5e4b1242015-08-06 22:53:06 -06002735// Given a member type of a struct, realign the current offset for it, and compute
2736// the next (not yet aligned) offset for the next member, which will get aligned
2737// on the next call.
2738// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2739// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2740// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002741void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002742 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002743{
2744 // this will get a positive value when deemed necessary
2745 nextOffset = -1;
2746
John Kessenich5e4b1242015-08-06 22:53:06 -06002747 // override anything in currentOffset with user-set offset
2748 if (memberType.getQualifier().hasOffset())
2749 currentOffset = memberType.getQualifier().layoutOffset;
2750
2751 // It could be that current linker usage in glslang updated all the layoutOffset,
2752 // in which case the following code does not matter. But, that's not quite right
2753 // once cross-compilation unit GLSL validation is done, as the original user
2754 // settings are needed in layoutOffset, and then the following will come into play.
2755
John Kessenichf85e8062015-12-19 13:57:10 -07002756 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002757 if (! memberType.getQualifier().hasOffset())
2758 currentOffset = -1;
2759
2760 return;
2761 }
2762
John Kessenichf85e8062015-12-19 13:57:10 -07002763 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002764 if (currentOffset < 0)
2765 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002766
John Kessenich5e4b1242015-08-06 22:53:06 -06002767 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2768 // but possibly not yet correctly aligned.
2769
2770 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002771 int dummyStride;
2772 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002773
2774 // Adjust alignment for HLSL rules
2775 if (glslangIntermediate->usingHlslOFfsets() &&
2776 ! memberType.isArray() && memberType.isVector()) {
2777 int dummySize;
2778 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2779 if (componentAlignment <= 4)
2780 memberAlignment = componentAlignment;
2781 }
2782
2783 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002784 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002785
2786 // Bump up to vec4 if there is a bad straddle
2787 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2788 glslang::RoundToPow2(currentOffset, 16);
2789
John Kessenich5e4b1242015-08-06 22:53:06 -06002790 nextOffset = currentOffset + memberSize;
2791}
2792
David Netoa901ffe2016-06-08 14:11:40 +01002793void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002794{
David Netoa901ffe2016-06-08 14:11:40 +01002795 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2796 switch (glslangBuiltIn)
2797 {
2798 case glslang::EbvClipDistance:
2799 case glslang::EbvCullDistance:
2800 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002801#ifdef NV_EXTENSIONS
2802 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002803 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002804 case glslang::EbvViewportMaskNV:
2805 case glslang::EbvSecondaryPositionNV:
2806 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002807 case glslang::EbvPositionPerViewNV:
2808 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002809#endif
David Netoa901ffe2016-06-08 14:11:40 +01002810 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2811 // Alternately, we could just call this for any glslang built-in, since the
2812 // capability already guards against duplicates.
2813 TranslateBuiltInDecoration(glslangBuiltIn, false);
2814 break;
2815 default:
2816 // Capabilities were already generated when the struct was declared.
2817 break;
2818 }
John Kessenichebb50532016-05-16 19:22:05 -06002819}
2820
John Kessenich6fccb3c2016-09-19 16:01:41 -06002821bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002822{
John Kessenicheee9d532016-09-19 18:09:30 -06002823 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002824}
2825
2826// Make all the functions, skeletally, without actually visiting their bodies.
2827void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2828{
2829 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2830 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002831 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002832 continue;
2833
2834 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002835 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002836 //
qining25262b32016-05-06 17:25:16 -04002837 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002838 // function. What it is an address of varies:
2839 //
John Kessenich4bf71552016-09-02 11:20:21 -06002840 // - "in" parameters not marked as "const" can be written to without modifying the calling
2841 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002842 //
2843 // - "const in" parameters can just be the r-value, as no writes need occur.
2844 //
John Kessenich4bf71552016-09-02 11:20:21 -06002845 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2846 // 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 -06002847
2848 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002849 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002850 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2851
John Kessenich37789792017-03-21 23:56:40 -06002852 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName;
2853
John Kessenich140f3df2015-06-26 16:58:36 -06002854 for (int p = 0; p < (int)parameters.size(); ++p) {
2855 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2856 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002857 // can we pass by reference?
2858 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002859 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002860 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002861 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06002862 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002863 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002864 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2865 else
John Kessenich4bf71552016-09-02 11:20:21 -06002866 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002867 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002868 paramTypes.push_back(typeId);
2869 }
2870
2871 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002872 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2873 convertGlslangToSpvType(glslFunction->getType()),
2874 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002875 if (implicitThis)
2876 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002877
2878 // Track function to emit/call later
2879 functionMap[glslFunction->getName().c_str()] = function;
2880
2881 // Set the parameter id's
2882 for (int p = 0; p < (int)parameters.size(); ++p) {
2883 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2884 // give a name too
2885 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2886 }
2887 }
2888}
2889
2890// Process all the initializers, while skipping the functions and link objects
2891void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2892{
2893 builder.setBuildPoint(shaderEntry->getLastBlock());
2894 for (int i = 0; i < (int)initializers.size(); ++i) {
2895 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2896 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2897
2898 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002899 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002900 initializer->traverse(this);
2901 }
2902 }
2903}
2904
2905// Process all the functions, while skipping initializers.
2906void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2907{
2908 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2909 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002910 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002911 node->traverse(this);
2912 }
2913}
2914
2915void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2916{
qining25262b32016-05-06 17:25:16 -04002917 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002918 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002919 currentFunction = functionMap[node->getName().c_str()];
2920 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002921 builder.setBuildPoint(functionBlock);
2922}
2923
Rex Xu04db3f52015-09-16 11:44:02 +08002924void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002925{
Rex Xufc618912015-09-09 16:42:49 +08002926 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002927
2928 glslang::TSampler sampler = {};
2929 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002930 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002931 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2932 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2933 }
2934
John Kessenich140f3df2015-06-26 16:58:36 -06002935 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2936 builder.clearAccessChain();
2937 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002938
2939 // Special case l-value operands
2940 bool lvalue = false;
2941 switch (node.getOp()) {
2942 case glslang::EOpImageAtomicAdd:
2943 case glslang::EOpImageAtomicMin:
2944 case glslang::EOpImageAtomicMax:
2945 case glslang::EOpImageAtomicAnd:
2946 case glslang::EOpImageAtomicOr:
2947 case glslang::EOpImageAtomicXor:
2948 case glslang::EOpImageAtomicExchange:
2949 case glslang::EOpImageAtomicCompSwap:
2950 if (i == 0)
2951 lvalue = true;
2952 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002953 case glslang::EOpSparseImageLoad:
2954 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2955 lvalue = true;
2956 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002957 case glslang::EOpSparseTexture:
2958 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2959 lvalue = true;
2960 break;
2961 case glslang::EOpSparseTextureClamp:
2962 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2963 lvalue = true;
2964 break;
2965 case glslang::EOpSparseTextureLod:
2966 case glslang::EOpSparseTextureOffset:
2967 if (i == 3)
2968 lvalue = true;
2969 break;
2970 case glslang::EOpSparseTextureFetch:
2971 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2972 lvalue = true;
2973 break;
2974 case glslang::EOpSparseTextureFetchOffset:
2975 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2976 lvalue = true;
2977 break;
2978 case glslang::EOpSparseTextureLodOffset:
2979 case glslang::EOpSparseTextureGrad:
2980 case glslang::EOpSparseTextureOffsetClamp:
2981 if (i == 4)
2982 lvalue = true;
2983 break;
2984 case glslang::EOpSparseTextureGradOffset:
2985 case glslang::EOpSparseTextureGradClamp:
2986 if (i == 5)
2987 lvalue = true;
2988 break;
2989 case glslang::EOpSparseTextureGradOffsetClamp:
2990 if (i == 6)
2991 lvalue = true;
2992 break;
2993 case glslang::EOpSparseTextureGather:
2994 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2995 lvalue = true;
2996 break;
2997 case glslang::EOpSparseTextureGatherOffset:
2998 case glslang::EOpSparseTextureGatherOffsets:
2999 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3000 lvalue = true;
3001 break;
Rex Xufc618912015-09-09 16:42:49 +08003002 default:
3003 break;
3004 }
3005
Rex Xu6b86d492015-09-16 17:48:22 +08003006 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003007 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003008 else
John Kessenich32cfd492016-02-02 12:37:46 -07003009 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003010 }
3011}
3012
John Kessenichfc51d282015-08-19 13:34:18 -06003013void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003014{
John Kessenichfc51d282015-08-19 13:34:18 -06003015 builder.clearAccessChain();
3016 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003017 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003018}
John Kessenich140f3df2015-06-26 16:58:36 -06003019
John Kessenichfc51d282015-08-19 13:34:18 -06003020spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3021{
Rex Xufc618912015-09-09 16:42:49 +08003022 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06003023 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003024 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003025 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003026
John Kessenichfc51d282015-08-19 13:34:18 -06003027 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003028 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3029 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3030 std::vector<spv::Id> arguments;
3031 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003032 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003033 else
3034 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003035 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003036
3037 spv::Builder::TextureParameters params = { };
3038 params.sampler = arguments[0];
3039
Rex Xu04db3f52015-09-16 11:44:02 +08003040 glslang::TCrackedTextureOp cracked;
3041 node->crackTexture(sampler, cracked);
3042
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003043 const bool isUnsignedResult =
3044 node->getType().getBasicType() == glslang::EbtUint64 ||
3045 node->getType().getBasicType() == glslang::EbtUint;
3046
John Kessenichfc51d282015-08-19 13:34:18 -06003047 // Check for queries
3048 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003049 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3050 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003051 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003052
John Kessenichfc51d282015-08-19 13:34:18 -06003053 switch (node->getOp()) {
3054 case glslang::EOpImageQuerySize:
3055 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003056 if (arguments.size() > 1) {
3057 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003058 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003059 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003060 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003061 case glslang::EOpImageQuerySamples:
3062 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003063 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003064 case glslang::EOpTextureQueryLod:
3065 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003066 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003067 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003068 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003069 case glslang::EOpSparseTexelsResident:
3070 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003071 default:
3072 assert(0);
3073 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003074 }
John Kessenich140f3df2015-06-26 16:58:36 -06003075 }
3076
Rex Xufc618912015-09-09 16:42:49 +08003077 // Check for image functions other than queries
3078 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003079 std::vector<spv::Id> operands;
3080 auto opIt = arguments.begin();
3081 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003082
3083 // Handle subpass operations
3084 // TODO: GLSL should change to have the "MS" only on the type rather than the
3085 // built-in function.
3086 if (cracked.subpass) {
3087 // add on the (0,0) coordinate
3088 spv::Id zero = builder.makeIntConstant(0);
3089 std::vector<spv::Id> comps;
3090 comps.push_back(zero);
3091 comps.push_back(zero);
3092 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3093 if (sampler.ms) {
3094 operands.push_back(spv::ImageOperandsSampleMask);
3095 operands.push_back(*(opIt++));
3096 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003097 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003098 }
3099
John Kessenich56bab042015-09-16 10:54:31 -06003100 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003101 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003102 if (sampler.ms) {
3103 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003104 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003105 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003106 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3107 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003108 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003109 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003110 if (sampler.ms) {
3111 operands.push_back(*(opIt + 1));
3112 operands.push_back(spv::ImageOperandsSampleMask);
3113 operands.push_back(*opIt);
3114 } else
3115 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003116 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003117 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3118 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003119 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003120 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3121 builder.addCapability(spv::CapabilitySparseResidency);
3122 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3123 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3124
3125 if (sampler.ms) {
3126 operands.push_back(spv::ImageOperandsSampleMask);
3127 operands.push_back(*opIt++);
3128 }
3129
3130 // Create the return type that was a special structure
3131 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003132 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003133 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3134 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3135
3136 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3137
3138 // Decode the return type
3139 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3140 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003141 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003142 // Process image atomic operations
3143
3144 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3145 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003146 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003147
John Kessenich8c8505c2016-07-26 12:50:38 -06003148 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003149 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003150
3151 std::vector<spv::Id> operands;
3152 operands.push_back(pointer);
3153 for (; opIt != arguments.end(); ++opIt)
3154 operands.push_back(*opIt);
3155
John Kessenich8c8505c2016-07-26 12:50:38 -06003156 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003157 }
3158 }
3159
3160 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003161 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003162 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3163
John Kessenichfc51d282015-08-19 13:34:18 -06003164 // check for bias argument
3165 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003166 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003167 int nonBiasArgCount = 2;
3168 if (cracked.offset)
3169 ++nonBiasArgCount;
3170 if (cracked.grad)
3171 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003172 if (cracked.lodClamp)
3173 ++nonBiasArgCount;
3174 if (sparse)
3175 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003176
3177 if ((int)arguments.size() > nonBiasArgCount)
3178 bias = true;
3179 }
3180
John Kessenicha5c33d62016-06-02 23:45:21 -06003181 // See if the sampler param should really be just the SPV image part
3182 if (cracked.fetch) {
3183 // a fetch needs to have the image extracted first
3184 if (builder.isSampledImage(params.sampler))
3185 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3186 }
3187
John Kessenichfc51d282015-08-19 13:34:18 -06003188 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003189
John Kessenichfc51d282015-08-19 13:34:18 -06003190 params.coords = arguments[1];
3191 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003192 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003193
3194 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003195 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003196 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003197 ++extraArgs;
3198 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003199 params.Dref = arguments[2];
3200 ++extraArgs;
3201 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003202 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003203 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003204 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003205 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003206 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003207 dRefComp = builder.getNumComponents(params.coords) - 1;
3208 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003209 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3210 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003211
3212 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003213 if (cracked.lod) {
3214 params.lod = arguments[2];
3215 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003216 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3217 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3218 noImplicitLod = true;
3219 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003220
3221 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003222 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003223 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003224 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003225 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003226
3227 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003228 if (cracked.grad) {
3229 params.gradX = arguments[2 + extraArgs];
3230 params.gradY = arguments[3 + extraArgs];
3231 extraArgs += 2;
3232 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003233
3234 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003235 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003236 params.offset = arguments[2 + extraArgs];
3237 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003238 } else if (cracked.offsets) {
3239 params.offsets = arguments[2 + extraArgs];
3240 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003241 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003242
3243 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003244 if (cracked.lodClamp) {
3245 params.lodClamp = arguments[2 + extraArgs];
3246 ++extraArgs;
3247 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003248
3249 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003250 if (sparse) {
3251 params.texelOut = arguments[2 + extraArgs];
3252 ++extraArgs;
3253 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003254
3255 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003256 if (bias) {
3257 params.bias = arguments[2 + extraArgs];
3258 ++extraArgs;
3259 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003260
3261 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003262 if (cracked.gather && ! sampler.shadow) {
3263 // default component is 0, if missing, otherwise an argument
3264 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003265 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003266 ++extraArgs;
3267 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003268 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003269 }
3270 }
John Kessenichfc51d282015-08-19 13:34:18 -06003271
John Kessenich65336482016-06-16 14:06:26 -06003272 // projective component (might not to move)
3273 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3274 // are divided by the last component of P."
3275 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3276 // unused components will appear after all used components."
3277 if (cracked.proj) {
3278 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3279 int projTargetComp;
3280 switch (sampler.dim) {
3281 case glslang::Esd1D: projTargetComp = 1; break;
3282 case glslang::Esd2D: projTargetComp = 2; break;
3283 case glslang::EsdRect: projTargetComp = 2; break;
3284 default: projTargetComp = projSourceComp; break;
3285 }
3286 // copy the projective coordinate if we have to
3287 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003288 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003289 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3290 projSourceComp);
3291 params.coords = builder.createCompositeInsert(projComp, params.coords,
3292 builder.getTypeId(params.coords), projTargetComp);
3293 }
3294 }
3295
John Kessenich8c8505c2016-07-26 12:50:38 -06003296 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003297}
3298
3299spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3300{
3301 // Grab the function's pointer from the previously created function
3302 spv::Function* function = functionMap[node->getName().c_str()];
3303 if (! function)
3304 return 0;
3305
3306 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3307 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3308
3309 // See comments in makeFunctions() for details about the semantics for parameter passing.
3310 //
3311 // These imply we need a four step process:
3312 // 1. Evaluate the arguments
3313 // 2. Allocate and make copies of in, out, and inout arguments
3314 // 3. Make the call
3315 // 4. Copy back the results
3316
3317 // 1. Evaluate the arguments
3318 std::vector<spv::Builder::AccessChain> lValues;
3319 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003320 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003321 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003322 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003323 // build l-value
3324 builder.clearAccessChain();
3325 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003326 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003327 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003328 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003329 // save l-value
3330 lValues.push_back(builder.getAccessChain());
3331 } else {
3332 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003333 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003334 }
3335 }
3336
3337 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3338 // copy the original into that space.
3339 //
3340 // Also, build up the list of actual arguments to pass in for the call
3341 int lValueCount = 0;
3342 int rValueCount = 0;
3343 std::vector<spv::Id> spvArgs;
3344 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003345 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003346 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003347 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003348 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3349 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003350 builder.setAccessChain(lValues[lValueCount]);
3351 arg = builder.accessChainGetLValue();
3352 ++lValueCount;
3353 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003354 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003355 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3356 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3357 // need to copy the input into output space
3358 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003359 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003360 builder.clearAccessChain();
3361 builder.setAccessChainLValue(arg);
3362 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003363 }
3364 ++lValueCount;
3365 } else {
3366 arg = rValues[rValueCount];
3367 ++rValueCount;
3368 }
3369 spvArgs.push_back(arg);
3370 }
3371
3372 // 3. Make the call.
3373 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003374 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003375
3376 // 4. Copy back out an "out" arguments.
3377 lValueCount = 0;
3378 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003379 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003380 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3381 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3382 spv::Id copy = builder.createLoad(spvArgs[a]);
3383 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003384 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003385 }
3386 ++lValueCount;
3387 }
3388 }
3389
3390 return result;
3391}
3392
3393// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003394spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3395 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003396 spv::Id typeId, spv::Id left, spv::Id right,
3397 glslang::TBasicType typeProxy, bool reduceComparison)
3398{
Rex Xu8ff43de2016-04-22 16:51:45 +08003399 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003400#ifdef AMD_EXTENSIONS
3401 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3402#else
John Kessenich140f3df2015-06-26 16:58:36 -06003403 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003404#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003405 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003406
3407 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003408 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003409 bool comparison = false;
3410
3411 switch (op) {
3412 case glslang::EOpAdd:
3413 case glslang::EOpAddAssign:
3414 if (isFloat)
3415 binOp = spv::OpFAdd;
3416 else
3417 binOp = spv::OpIAdd;
3418 break;
3419 case glslang::EOpSub:
3420 case glslang::EOpSubAssign:
3421 if (isFloat)
3422 binOp = spv::OpFSub;
3423 else
3424 binOp = spv::OpISub;
3425 break;
3426 case glslang::EOpMul:
3427 case glslang::EOpMulAssign:
3428 if (isFloat)
3429 binOp = spv::OpFMul;
3430 else
3431 binOp = spv::OpIMul;
3432 break;
3433 case glslang::EOpVectorTimesScalar:
3434 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003435 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003436 if (builder.isVector(right))
3437 std::swap(left, right);
3438 assert(builder.isScalar(right));
3439 needMatchingVectors = false;
3440 binOp = spv::OpVectorTimesScalar;
3441 } else
3442 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003443 break;
3444 case glslang::EOpVectorTimesMatrix:
3445 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003446 binOp = spv::OpVectorTimesMatrix;
3447 break;
3448 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003449 binOp = spv::OpMatrixTimesVector;
3450 break;
3451 case glslang::EOpMatrixTimesScalar:
3452 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003453 binOp = spv::OpMatrixTimesScalar;
3454 break;
3455 case glslang::EOpMatrixTimesMatrix:
3456 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003457 binOp = spv::OpMatrixTimesMatrix;
3458 break;
3459 case glslang::EOpOuterProduct:
3460 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003461 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003462 break;
3463
3464 case glslang::EOpDiv:
3465 case glslang::EOpDivAssign:
3466 if (isFloat)
3467 binOp = spv::OpFDiv;
3468 else if (isUnsigned)
3469 binOp = spv::OpUDiv;
3470 else
3471 binOp = spv::OpSDiv;
3472 break;
3473 case glslang::EOpMod:
3474 case glslang::EOpModAssign:
3475 if (isFloat)
3476 binOp = spv::OpFMod;
3477 else if (isUnsigned)
3478 binOp = spv::OpUMod;
3479 else
3480 binOp = spv::OpSMod;
3481 break;
3482 case glslang::EOpRightShift:
3483 case glslang::EOpRightShiftAssign:
3484 if (isUnsigned)
3485 binOp = spv::OpShiftRightLogical;
3486 else
3487 binOp = spv::OpShiftRightArithmetic;
3488 break;
3489 case glslang::EOpLeftShift:
3490 case glslang::EOpLeftShiftAssign:
3491 binOp = spv::OpShiftLeftLogical;
3492 break;
3493 case glslang::EOpAnd:
3494 case glslang::EOpAndAssign:
3495 binOp = spv::OpBitwiseAnd;
3496 break;
3497 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003498 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003499 binOp = spv::OpLogicalAnd;
3500 break;
3501 case glslang::EOpInclusiveOr:
3502 case glslang::EOpInclusiveOrAssign:
3503 binOp = spv::OpBitwiseOr;
3504 break;
3505 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003506 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003507 binOp = spv::OpLogicalOr;
3508 break;
3509 case glslang::EOpExclusiveOr:
3510 case glslang::EOpExclusiveOrAssign:
3511 binOp = spv::OpBitwiseXor;
3512 break;
3513 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003514 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003515 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003516 break;
3517
3518 case glslang::EOpLessThan:
3519 case glslang::EOpGreaterThan:
3520 case glslang::EOpLessThanEqual:
3521 case glslang::EOpGreaterThanEqual:
3522 case glslang::EOpEqual:
3523 case glslang::EOpNotEqual:
3524 case glslang::EOpVectorEqual:
3525 case glslang::EOpVectorNotEqual:
3526 comparison = true;
3527 break;
3528 default:
3529 break;
3530 }
3531
John Kessenich7c1aa102015-10-15 13:29:11 -06003532 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003533 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003534 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003535 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003536 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003537
3538 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003539 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003540 builder.promoteScalar(precision, left, right);
3541
qining25262b32016-05-06 17:25:16 -04003542 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3543 addDecoration(result, noContraction);
3544 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003545 }
3546
3547 if (! comparison)
3548 return 0;
3549
John Kessenich7c1aa102015-10-15 13:29:11 -06003550 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003551
John Kessenich4583b612016-08-07 19:14:22 -06003552 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3553 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003554 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003555
3556 switch (op) {
3557 case glslang::EOpLessThan:
3558 if (isFloat)
3559 binOp = spv::OpFOrdLessThan;
3560 else if (isUnsigned)
3561 binOp = spv::OpULessThan;
3562 else
3563 binOp = spv::OpSLessThan;
3564 break;
3565 case glslang::EOpGreaterThan:
3566 if (isFloat)
3567 binOp = spv::OpFOrdGreaterThan;
3568 else if (isUnsigned)
3569 binOp = spv::OpUGreaterThan;
3570 else
3571 binOp = spv::OpSGreaterThan;
3572 break;
3573 case glslang::EOpLessThanEqual:
3574 if (isFloat)
3575 binOp = spv::OpFOrdLessThanEqual;
3576 else if (isUnsigned)
3577 binOp = spv::OpULessThanEqual;
3578 else
3579 binOp = spv::OpSLessThanEqual;
3580 break;
3581 case glslang::EOpGreaterThanEqual:
3582 if (isFloat)
3583 binOp = spv::OpFOrdGreaterThanEqual;
3584 else if (isUnsigned)
3585 binOp = spv::OpUGreaterThanEqual;
3586 else
3587 binOp = spv::OpSGreaterThanEqual;
3588 break;
3589 case glslang::EOpEqual:
3590 case glslang::EOpVectorEqual:
3591 if (isFloat)
3592 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003593 else if (isBool)
3594 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003595 else
3596 binOp = spv::OpIEqual;
3597 break;
3598 case glslang::EOpNotEqual:
3599 case glslang::EOpVectorNotEqual:
3600 if (isFloat)
3601 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003602 else if (isBool)
3603 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003604 else
3605 binOp = spv::OpINotEqual;
3606 break;
3607 default:
3608 break;
3609 }
3610
qining25262b32016-05-06 17:25:16 -04003611 if (binOp != spv::OpNop) {
3612 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3613 addDecoration(result, noContraction);
3614 return builder.setPrecision(result, precision);
3615 }
John Kessenich140f3df2015-06-26 16:58:36 -06003616
3617 return 0;
3618}
3619
John Kessenich04bb8a02015-12-12 12:28:14 -07003620//
3621// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3622// These can be any of:
3623//
3624// matrix * scalar
3625// scalar * matrix
3626// matrix * matrix linear algebraic
3627// matrix * vector
3628// vector * matrix
3629// matrix * matrix componentwise
3630// matrix op matrix op in {+, -, /}
3631// matrix op scalar op in {+, -, /}
3632// scalar op matrix op in {+, -, /}
3633//
qining25262b32016-05-06 17:25:16 -04003634spv::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 -07003635{
3636 bool firstClass = true;
3637
3638 // First, handle first-class matrix operations (* and matrix/scalar)
3639 switch (op) {
3640 case spv::OpFDiv:
3641 if (builder.isMatrix(left) && builder.isScalar(right)) {
3642 // turn matrix / scalar into a multiply...
3643 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3644 op = spv::OpMatrixTimesScalar;
3645 } else
3646 firstClass = false;
3647 break;
3648 case spv::OpMatrixTimesScalar:
3649 if (builder.isMatrix(right))
3650 std::swap(left, right);
3651 assert(builder.isScalar(right));
3652 break;
3653 case spv::OpVectorTimesMatrix:
3654 assert(builder.isVector(left));
3655 assert(builder.isMatrix(right));
3656 break;
3657 case spv::OpMatrixTimesVector:
3658 assert(builder.isMatrix(left));
3659 assert(builder.isVector(right));
3660 break;
3661 case spv::OpMatrixTimesMatrix:
3662 assert(builder.isMatrix(left));
3663 assert(builder.isMatrix(right));
3664 break;
3665 default:
3666 firstClass = false;
3667 break;
3668 }
3669
qining25262b32016-05-06 17:25:16 -04003670 if (firstClass) {
3671 spv::Id result = builder.createBinOp(op, typeId, left, right);
3672 addDecoration(result, noContraction);
3673 return builder.setPrecision(result, precision);
3674 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003675
LoopDawg592860c2016-06-09 08:57:35 -06003676 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003677 // The result type of all of them is the same type as the (a) matrix operand.
3678 // The algorithm is to:
3679 // - break the matrix(es) into vectors
3680 // - smear any scalar to a vector
3681 // - do vector operations
3682 // - make a matrix out the vector results
3683 switch (op) {
3684 case spv::OpFAdd:
3685 case spv::OpFSub:
3686 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003687 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003688 case spv::OpFMul:
3689 {
3690 // one time set up...
3691 bool leftMat = builder.isMatrix(left);
3692 bool rightMat = builder.isMatrix(right);
3693 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3694 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3695 spv::Id scalarType = builder.getScalarTypeId(typeId);
3696 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3697 std::vector<spv::Id> results;
3698 spv::Id smearVec = spv::NoResult;
3699 if (builder.isScalar(left))
3700 smearVec = builder.smearScalar(precision, left, vecType);
3701 else if (builder.isScalar(right))
3702 smearVec = builder.smearScalar(precision, right, vecType);
3703
3704 // do each vector op
3705 for (unsigned int c = 0; c < numCols; ++c) {
3706 std::vector<unsigned int> indexes;
3707 indexes.push_back(c);
3708 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3709 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003710 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3711 addDecoration(result, noContraction);
3712 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003713 }
3714
3715 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003716 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003717 }
3718 default:
3719 assert(0);
3720 return spv::NoResult;
3721 }
3722}
3723
qining25262b32016-05-06 17:25:16 -04003724spv::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 -06003725{
3726 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003727 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003728 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003729 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003730#ifdef AMD_EXTENSIONS
3731 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3732#else
Rex Xu04db3f52015-09-16 11:44:02 +08003733 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003734#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003735
3736 switch (op) {
3737 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003738 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003739 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003740 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003741 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003742 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003743 unaryOp = spv::OpSNegate;
3744 break;
3745
3746 case glslang::EOpLogicalNot:
3747 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003748 unaryOp = spv::OpLogicalNot;
3749 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003750 case glslang::EOpBitwiseNot:
3751 unaryOp = spv::OpNot;
3752 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003753
John Kessenich140f3df2015-06-26 16:58:36 -06003754 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003755 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003756 break;
3757 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003758 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003759 break;
3760 case glslang::EOpTranspose:
3761 unaryOp = spv::OpTranspose;
3762 break;
3763
3764 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003765 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003766 break;
3767 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003768 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003769 break;
3770 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003771 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003772 break;
3773 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003774 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003775 break;
3776 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003777 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003778 break;
3779 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003780 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003781 break;
3782 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003783 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003784 break;
3785 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003786 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003787 break;
3788
3789 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003790 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003791 break;
3792 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003793 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003794 break;
3795 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003796 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003797 break;
3798 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003799 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003800 break;
3801 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003802 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003803 break;
3804 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003805 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003806 break;
3807
3808 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003809 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003810 break;
3811 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003812 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003813 break;
3814
3815 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003816 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003817 break;
3818 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003819 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003820 break;
3821 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003822 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003823 break;
3824 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003825 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003826 break;
3827 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003828 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003829 break;
3830 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003831 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003832 break;
3833
3834 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003835 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003836 break;
3837 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003838 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003839 break;
3840 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003841 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003842 break;
3843 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003844 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003845 break;
3846 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003847 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003848 break;
3849 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003850 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003851 break;
3852
3853 case glslang::EOpIsNan:
3854 unaryOp = spv::OpIsNan;
3855 break;
3856 case glslang::EOpIsInf:
3857 unaryOp = spv::OpIsInf;
3858 break;
LoopDawg592860c2016-06-09 08:57:35 -06003859 case glslang::EOpIsFinite:
3860 unaryOp = spv::OpIsFinite;
3861 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003862
Rex Xucbc426e2015-12-15 16:03:10 +08003863 case glslang::EOpFloatBitsToInt:
3864 case glslang::EOpFloatBitsToUint:
3865 case glslang::EOpIntBitsToFloat:
3866 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003867 case glslang::EOpDoubleBitsToInt64:
3868 case glslang::EOpDoubleBitsToUint64:
3869 case glslang::EOpInt64BitsToDouble:
3870 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003871 unaryOp = spv::OpBitcast;
3872 break;
3873
John Kessenich140f3df2015-06-26 16:58:36 -06003874 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003875 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003876 break;
3877 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003878 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003879 break;
3880 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003881 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003882 break;
3883 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003884 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003885 break;
3886 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003887 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003888 break;
3889 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003890 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003891 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003892 case glslang::EOpPackSnorm4x8:
3893 libCall = spv::GLSLstd450PackSnorm4x8;
3894 break;
3895 case glslang::EOpUnpackSnorm4x8:
3896 libCall = spv::GLSLstd450UnpackSnorm4x8;
3897 break;
3898 case glslang::EOpPackUnorm4x8:
3899 libCall = spv::GLSLstd450PackUnorm4x8;
3900 break;
3901 case glslang::EOpUnpackUnorm4x8:
3902 libCall = spv::GLSLstd450UnpackUnorm4x8;
3903 break;
3904 case glslang::EOpPackDouble2x32:
3905 libCall = spv::GLSLstd450PackDouble2x32;
3906 break;
3907 case glslang::EOpUnpackDouble2x32:
3908 libCall = spv::GLSLstd450UnpackDouble2x32;
3909 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003910
Rex Xu8ff43de2016-04-22 16:51:45 +08003911 case glslang::EOpPackInt2x32:
3912 case glslang::EOpUnpackInt2x32:
3913 case glslang::EOpPackUint2x32:
3914 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003915 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003916 break;
3917
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003918#ifdef AMD_EXTENSIONS
3919 case glslang::EOpPackFloat2x16:
3920 case glslang::EOpUnpackFloat2x16:
3921 unaryOp = spv::OpBitcast;
3922 break;
3923#endif
3924
John Kessenich140f3df2015-06-26 16:58:36 -06003925 case glslang::EOpDPdx:
3926 unaryOp = spv::OpDPdx;
3927 break;
3928 case glslang::EOpDPdy:
3929 unaryOp = spv::OpDPdy;
3930 break;
3931 case glslang::EOpFwidth:
3932 unaryOp = spv::OpFwidth;
3933 break;
3934 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003935 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003936 unaryOp = spv::OpDPdxFine;
3937 break;
3938 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003939 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003940 unaryOp = spv::OpDPdyFine;
3941 break;
3942 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003943 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003944 unaryOp = spv::OpFwidthFine;
3945 break;
3946 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003947 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003948 unaryOp = spv::OpDPdxCoarse;
3949 break;
3950 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003951 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003952 unaryOp = spv::OpDPdyCoarse;
3953 break;
3954 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003955 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003956 unaryOp = spv::OpFwidthCoarse;
3957 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003958 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003959 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003960 libCall = spv::GLSLstd450InterpolateAtCentroid;
3961 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003962 case glslang::EOpAny:
3963 unaryOp = spv::OpAny;
3964 break;
3965 case glslang::EOpAll:
3966 unaryOp = spv::OpAll;
3967 break;
3968
3969 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003970 if (isFloat)
3971 libCall = spv::GLSLstd450FAbs;
3972 else
3973 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003974 break;
3975 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003976 if (isFloat)
3977 libCall = spv::GLSLstd450FSign;
3978 else
3979 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003980 break;
3981
John Kessenichfc51d282015-08-19 13:34:18 -06003982 case glslang::EOpAtomicCounterIncrement:
3983 case glslang::EOpAtomicCounterDecrement:
3984 case glslang::EOpAtomicCounter:
3985 {
3986 // Handle all of the atomics in one place, in createAtomicOperation()
3987 std::vector<spv::Id> operands;
3988 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003989 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003990 }
3991
John Kessenichfc51d282015-08-19 13:34:18 -06003992 case glslang::EOpBitFieldReverse:
3993 unaryOp = spv::OpBitReverse;
3994 break;
3995 case glslang::EOpBitCount:
3996 unaryOp = spv::OpBitCount;
3997 break;
3998 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003999 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004000 break;
4001 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004002 if (isUnsigned)
4003 libCall = spv::GLSLstd450FindUMsb;
4004 else
4005 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004006 break;
4007
Rex Xu574ab042016-04-14 16:53:07 +08004008 case glslang::EOpBallot:
4009 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004010 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004011 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004012 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004013#ifdef AMD_EXTENSIONS
4014 case glslang::EOpMinInvocations:
4015 case glslang::EOpMaxInvocations:
4016 case glslang::EOpAddInvocations:
4017 case glslang::EOpMinInvocationsNonUniform:
4018 case glslang::EOpMaxInvocationsNonUniform:
4019 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004020 case glslang::EOpMinInvocationsInclusiveScan:
4021 case glslang::EOpMaxInvocationsInclusiveScan:
4022 case glslang::EOpAddInvocationsInclusiveScan:
4023 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4024 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4025 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4026 case glslang::EOpMinInvocationsExclusiveScan:
4027 case glslang::EOpMaxInvocationsExclusiveScan:
4028 case glslang::EOpAddInvocationsExclusiveScan:
4029 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4030 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4031 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004032#endif
Rex Xu51596642016-09-21 18:56:12 +08004033 {
4034 std::vector<spv::Id> operands;
4035 operands.push_back(operand);
4036 return createInvocationsOperation(op, typeId, operands, typeProxy);
4037 }
Rex Xu9d93a232016-05-05 12:30:44 +08004038
4039#ifdef AMD_EXTENSIONS
4040 case glslang::EOpMbcnt:
4041 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4042 libCall = spv::MbcntAMD;
4043 break;
4044
4045 case glslang::EOpCubeFaceIndex:
4046 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4047 libCall = spv::CubeFaceIndexAMD;
4048 break;
4049
4050 case glslang::EOpCubeFaceCoord:
4051 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4052 libCall = spv::CubeFaceCoordAMD;
4053 break;
4054#endif
Rex Xu338b1852016-05-05 20:38:33 +08004055
John Kessenich140f3df2015-06-26 16:58:36 -06004056 default:
4057 return 0;
4058 }
4059
4060 spv::Id id;
4061 if (libCall >= 0) {
4062 std::vector<spv::Id> args;
4063 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004064 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004065 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004066 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004067 }
John Kessenich140f3df2015-06-26 16:58:36 -06004068
qining25262b32016-05-06 17:25:16 -04004069 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004070 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004071}
4072
John Kessenich7a53f762016-01-20 11:19:27 -07004073// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004074spv::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 -07004075{
4076 // Handle unary operations vector by vector.
4077 // The result type is the same type as the original type.
4078 // The algorithm is to:
4079 // - break the matrix into vectors
4080 // - apply the operation to each vector
4081 // - make a matrix out the vector results
4082
4083 // get the types sorted out
4084 int numCols = builder.getNumColumns(operand);
4085 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004086 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4087 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004088 std::vector<spv::Id> results;
4089
4090 // do each vector op
4091 for (int c = 0; c < numCols; ++c) {
4092 std::vector<unsigned int> indexes;
4093 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004094 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4095 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4096 addDecoration(destVec, noContraction);
4097 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004098 }
4099
4100 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004101 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004102}
4103
Rex Xu73e3ce72016-04-27 18:48:17 +08004104spv::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 -06004105{
4106 spv::Op convOp = spv::OpNop;
4107 spv::Id zero = 0;
4108 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004109 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004110
4111 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4112
4113 switch (op) {
4114 case glslang::EOpConvIntToBool:
4115 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004116 case glslang::EOpConvInt64ToBool:
4117 case glslang::EOpConvUint64ToBool:
4118 zero = (op == glslang::EOpConvInt64ToBool ||
4119 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004120 zero = makeSmearedConstant(zero, vectorSize);
4121 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4122
4123 case glslang::EOpConvFloatToBool:
4124 zero = builder.makeFloatConstant(0.0F);
4125 zero = makeSmearedConstant(zero, vectorSize);
4126 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4127
4128 case glslang::EOpConvDoubleToBool:
4129 zero = builder.makeDoubleConstant(0.0);
4130 zero = makeSmearedConstant(zero, vectorSize);
4131 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4132
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004133#ifdef AMD_EXTENSIONS
4134 case glslang::EOpConvFloat16ToBool:
4135 zero = builder.makeFloat16Constant(0.0F);
4136 zero = makeSmearedConstant(zero, vectorSize);
4137 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4138#endif
4139
John Kessenich140f3df2015-06-26 16:58:36 -06004140 case glslang::EOpConvBoolToFloat:
4141 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004142 zero = builder.makeFloatConstant(0.0F);
4143 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004144 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004145
John Kessenich140f3df2015-06-26 16:58:36 -06004146 case glslang::EOpConvBoolToDouble:
4147 convOp = spv::OpSelect;
4148 zero = builder.makeDoubleConstant(0.0);
4149 one = builder.makeDoubleConstant(1.0);
4150 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004151
4152#ifdef AMD_EXTENSIONS
4153 case glslang::EOpConvBoolToFloat16:
4154 convOp = spv::OpSelect;
4155 zero = builder.makeFloat16Constant(0.0F);
4156 one = builder.makeFloat16Constant(1.0F);
4157 break;
4158#endif
4159
John Kessenich140f3df2015-06-26 16:58:36 -06004160 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004161 case glslang::EOpConvBoolToInt64:
4162 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4163 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004164 convOp = spv::OpSelect;
4165 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004166
John Kessenich140f3df2015-06-26 16:58:36 -06004167 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004168 case glslang::EOpConvBoolToUint64:
4169 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4170 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004171 convOp = spv::OpSelect;
4172 break;
4173
4174 case glslang::EOpConvIntToFloat:
4175 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004176 case glslang::EOpConvInt64ToFloat:
4177 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004178#ifdef AMD_EXTENSIONS
4179 case glslang::EOpConvIntToFloat16:
4180 case glslang::EOpConvInt64ToFloat16:
4181#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004182 convOp = spv::OpConvertSToF;
4183 break;
4184
4185 case glslang::EOpConvUintToFloat:
4186 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004187 case glslang::EOpConvUint64ToFloat:
4188 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004189#ifdef AMD_EXTENSIONS
4190 case glslang::EOpConvUintToFloat16:
4191 case glslang::EOpConvUint64ToFloat16:
4192#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004193 convOp = spv::OpConvertUToF;
4194 break;
4195
4196 case glslang::EOpConvDoubleToFloat:
4197 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004198#ifdef AMD_EXTENSIONS
4199 case glslang::EOpConvDoubleToFloat16:
4200 case glslang::EOpConvFloat16ToDouble:
4201 case glslang::EOpConvFloatToFloat16:
4202 case glslang::EOpConvFloat16ToFloat:
4203#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004204 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004205 if (builder.isMatrixType(destType))
4206 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004207 break;
4208
4209 case glslang::EOpConvFloatToInt:
4210 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004211 case glslang::EOpConvFloatToInt64:
4212 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004213#ifdef AMD_EXTENSIONS
4214 case glslang::EOpConvFloat16ToInt:
4215 case glslang::EOpConvFloat16ToInt64:
4216#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004217 convOp = spv::OpConvertFToS;
4218 break;
4219
4220 case glslang::EOpConvUintToInt:
4221 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004222 case glslang::EOpConvUint64ToInt64:
4223 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004224 if (builder.isInSpecConstCodeGenMode()) {
4225 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004226 zero = (op == glslang::EOpConvUint64ToInt64 ||
4227 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004228 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004229 // Use OpIAdd, instead of OpBitcast to do the conversion when
4230 // generating for OpSpecConstantOp instruction.
4231 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4232 }
4233 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004234 convOp = spv::OpBitcast;
4235 break;
4236
4237 case glslang::EOpConvFloatToUint:
4238 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004239 case glslang::EOpConvFloatToUint64:
4240 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004241#ifdef AMD_EXTENSIONS
4242 case glslang::EOpConvFloat16ToUint:
4243 case glslang::EOpConvFloat16ToUint64:
4244#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004245 convOp = spv::OpConvertFToU;
4246 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004247
4248 case glslang::EOpConvIntToInt64:
4249 case glslang::EOpConvInt64ToInt:
4250 convOp = spv::OpSConvert;
4251 break;
4252
4253 case glslang::EOpConvUintToUint64:
4254 case glslang::EOpConvUint64ToUint:
4255 convOp = spv::OpUConvert;
4256 break;
4257
4258 case glslang::EOpConvIntToUint64:
4259 case glslang::EOpConvInt64ToUint:
4260 case glslang::EOpConvUint64ToInt:
4261 case glslang::EOpConvUintToInt64:
4262 // OpSConvert/OpUConvert + OpBitCast
4263 switch (op) {
4264 case glslang::EOpConvIntToUint64:
4265 convOp = spv::OpSConvert;
4266 type = builder.makeIntType(64);
4267 break;
4268 case glslang::EOpConvInt64ToUint:
4269 convOp = spv::OpSConvert;
4270 type = builder.makeIntType(32);
4271 break;
4272 case glslang::EOpConvUint64ToInt:
4273 convOp = spv::OpUConvert;
4274 type = builder.makeUintType(32);
4275 break;
4276 case glslang::EOpConvUintToInt64:
4277 convOp = spv::OpUConvert;
4278 type = builder.makeUintType(64);
4279 break;
4280 default:
4281 assert(0);
4282 break;
4283 }
4284
4285 if (vectorSize > 0)
4286 type = builder.makeVectorType(type, vectorSize);
4287
4288 operand = builder.createUnaryOp(convOp, type, operand);
4289
4290 if (builder.isInSpecConstCodeGenMode()) {
4291 // Build zero scalar or vector for OpIAdd.
4292 zero = (op == glslang::EOpConvIntToUint64 ||
4293 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4294 zero = makeSmearedConstant(zero, vectorSize);
4295 // Use OpIAdd, instead of OpBitcast to do the conversion when
4296 // generating for OpSpecConstantOp instruction.
4297 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4298 }
4299 // For normal run-time conversion instruction, use OpBitcast.
4300 convOp = spv::OpBitcast;
4301 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004302 default:
4303 break;
4304 }
4305
4306 spv::Id result = 0;
4307 if (convOp == spv::OpNop)
4308 return result;
4309
4310 if (convOp == spv::OpSelect) {
4311 zero = makeSmearedConstant(zero, vectorSize);
4312 one = makeSmearedConstant(one, vectorSize);
4313 result = builder.createTriOp(convOp, destType, operand, one, zero);
4314 } else
4315 result = builder.createUnaryOp(convOp, destType, operand);
4316
John Kessenich32cfd492016-02-02 12:37:46 -07004317 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004318}
4319
4320spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4321{
4322 if (vectorSize == 0)
4323 return constant;
4324
4325 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4326 std::vector<spv::Id> components;
4327 for (int c = 0; c < vectorSize; ++c)
4328 components.push_back(constant);
4329 return builder.makeCompositeConstant(vectorTypeId, components);
4330}
4331
John Kessenich426394d2015-07-23 10:22:48 -06004332// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004333spv::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 -06004334{
4335 spv::Op opCode = spv::OpNop;
4336
4337 switch (op) {
4338 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004339 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004340 opCode = spv::OpAtomicIAdd;
4341 break;
4342 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004343 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004344 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004345 break;
4346 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004347 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004348 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004349 break;
4350 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004351 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004352 opCode = spv::OpAtomicAnd;
4353 break;
4354 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004355 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004356 opCode = spv::OpAtomicOr;
4357 break;
4358 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004359 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004360 opCode = spv::OpAtomicXor;
4361 break;
4362 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004363 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004364 opCode = spv::OpAtomicExchange;
4365 break;
4366 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004367 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004368 opCode = spv::OpAtomicCompareExchange;
4369 break;
4370 case glslang::EOpAtomicCounterIncrement:
4371 opCode = spv::OpAtomicIIncrement;
4372 break;
4373 case glslang::EOpAtomicCounterDecrement:
4374 opCode = spv::OpAtomicIDecrement;
4375 break;
4376 case glslang::EOpAtomicCounter:
4377 opCode = spv::OpAtomicLoad;
4378 break;
4379 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004380 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004381 break;
4382 }
4383
4384 // Sort out the operands
4385 // - mapping from glslang -> SPV
4386 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004387 // - compare-exchange swaps the value and comparator
4388 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004389 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4390 auto opIt = operands.begin(); // walk the glslang operands
4391 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004392 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4393 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4394 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004395 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4396 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004397 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004398 spvAtomicOperands.push_back(*(opIt + 1));
4399 spvAtomicOperands.push_back(*opIt);
4400 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004401 }
John Kessenich426394d2015-07-23 10:22:48 -06004402
John Kessenich3e60a6f2015-09-14 22:45:16 -06004403 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004404 for (; opIt != operands.end(); ++opIt)
4405 spvAtomicOperands.push_back(*opIt);
4406
4407 return builder.createOp(opCode, typeId, spvAtomicOperands);
4408}
4409
John Kessenich91cef522016-05-05 16:45:40 -06004410// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004411spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004412{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004413#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004414 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004415 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004416#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004417
Rex Xu51596642016-09-21 18:56:12 +08004418 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004419 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004420 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4421
chaocf200da82016-12-20 12:44:35 -08004422 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4423 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004424 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4425 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004426 } else if (op == glslang::EOpAnyInvocation ||
4427 op == glslang::EOpAllInvocations ||
4428 op == glslang::EOpAllInvocationsEqual) {
4429 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4430 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004431 } else {
4432 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004433#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004434 if (op == glslang::EOpMinInvocationsNonUniform ||
4435 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004436 op == glslang::EOpAddInvocationsNonUniform ||
4437 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4438 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4439 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4440 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4441 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4442 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004443 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004444#endif
Rex Xu51596642016-09-21 18:56:12 +08004445
4446 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004447#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004448 switch (op) {
4449 case glslang::EOpMinInvocations:
4450 case glslang::EOpMaxInvocations:
4451 case glslang::EOpAddInvocations:
4452 case glslang::EOpMinInvocationsNonUniform:
4453 case glslang::EOpMaxInvocationsNonUniform:
4454 case glslang::EOpAddInvocationsNonUniform:
4455 groupOperation = spv::GroupOperationReduce;
4456 spvGroupOperands.push_back(groupOperation);
4457 break;
4458 case glslang::EOpMinInvocationsInclusiveScan:
4459 case glslang::EOpMaxInvocationsInclusiveScan:
4460 case glslang::EOpAddInvocationsInclusiveScan:
4461 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4462 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4463 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4464 groupOperation = spv::GroupOperationInclusiveScan;
4465 spvGroupOperands.push_back(groupOperation);
4466 break;
4467 case glslang::EOpMinInvocationsExclusiveScan:
4468 case glslang::EOpMaxInvocationsExclusiveScan:
4469 case glslang::EOpAddInvocationsExclusiveScan:
4470 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4471 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4472 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4473 groupOperation = spv::GroupOperationExclusiveScan;
4474 spvGroupOperands.push_back(groupOperation);
4475 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004476 default:
4477 break;
Rex Xu430ef402016-10-14 17:22:23 +08004478 }
Rex Xu9d93a232016-05-05 12:30:44 +08004479#endif
Rex Xu51596642016-09-21 18:56:12 +08004480 }
4481
4482 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4483 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004484
4485 switch (op) {
4486 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004487 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004488 break;
John Kessenich91cef522016-05-05 16:45:40 -06004489 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004490 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004491 break;
John Kessenich91cef522016-05-05 16:45:40 -06004492 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004493 opCode = spv::OpSubgroupAllEqualKHR;
4494 break;
Rex Xu51596642016-09-21 18:56:12 +08004495 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004496 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004497 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004498 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004499 break;
4500 case glslang::EOpReadFirstInvocation:
4501 opCode = spv::OpSubgroupFirstInvocationKHR;
4502 break;
4503 case glslang::EOpBallot:
4504 {
4505 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4506 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4507 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4508 //
4509 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4510 //
4511 spv::Id uintType = builder.makeUintType(32);
4512 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4513 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4514
4515 std::vector<spv::Id> components;
4516 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4517 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4518
4519 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4520 return builder.createUnaryOp(spv::OpBitcast, typeId,
4521 builder.createCompositeConstruct(uvec2Type, components));
4522 }
4523
Rex Xu9d93a232016-05-05 12:30:44 +08004524#ifdef AMD_EXTENSIONS
4525 case glslang::EOpMinInvocations:
4526 case glslang::EOpMaxInvocations:
4527 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004528 case glslang::EOpMinInvocationsInclusiveScan:
4529 case glslang::EOpMaxInvocationsInclusiveScan:
4530 case glslang::EOpAddInvocationsInclusiveScan:
4531 case glslang::EOpMinInvocationsExclusiveScan:
4532 case glslang::EOpMaxInvocationsExclusiveScan:
4533 case glslang::EOpAddInvocationsExclusiveScan:
4534 if (op == glslang::EOpMinInvocations ||
4535 op == glslang::EOpMinInvocationsInclusiveScan ||
4536 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004537 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004538 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004539 else {
4540 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004541 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004542 else
Rex Xu51596642016-09-21 18:56:12 +08004543 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004544 }
Rex Xu430ef402016-10-14 17:22:23 +08004545 } else if (op == glslang::EOpMaxInvocations ||
4546 op == glslang::EOpMaxInvocationsInclusiveScan ||
4547 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004548 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004549 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004550 else {
4551 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004552 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004553 else
Rex Xu51596642016-09-21 18:56:12 +08004554 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004555 }
4556 } else {
4557 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004558 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004559 else
Rex Xu51596642016-09-21 18:56:12 +08004560 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004561 }
4562
Rex Xu2bbbe062016-08-23 15:41:05 +08004563 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004564 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004565
4566 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004567 case glslang::EOpMinInvocationsNonUniform:
4568 case glslang::EOpMaxInvocationsNonUniform:
4569 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004570 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4571 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4572 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4573 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4574 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4575 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4576 if (op == glslang::EOpMinInvocationsNonUniform ||
4577 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4578 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004579 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004580 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004581 else {
4582 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004583 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004584 else
Rex Xu51596642016-09-21 18:56:12 +08004585 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004586 }
4587 }
Rex Xu430ef402016-10-14 17:22:23 +08004588 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4589 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4590 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004591 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004592 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004593 else {
4594 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004595 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004596 else
Rex Xu51596642016-09-21 18:56:12 +08004597 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004598 }
4599 }
4600 else {
4601 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004602 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004603 else
Rex Xu51596642016-09-21 18:56:12 +08004604 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004605 }
4606
Rex Xu2bbbe062016-08-23 15:41:05 +08004607 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004608 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004609
4610 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004611#endif
John Kessenich91cef522016-05-05 16:45:40 -06004612 default:
4613 logger->missingFunctionality("invocation operation");
4614 return spv::NoResult;
4615 }
Rex Xu51596642016-09-21 18:56:12 +08004616
4617 assert(opCode != spv::OpNop);
4618 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004619}
4620
Rex Xu2bbbe062016-08-23 15:41:05 +08004621// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004622spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004623{
Rex Xub7072052016-09-26 15:53:40 +08004624#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004625 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4626 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004627 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004628 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004629 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4630 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4631 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004632#else
4633 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4634 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004635 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4636 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004637#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004638
4639 // Handle group invocation operations scalar by scalar.
4640 // The result type is the same type as the original type.
4641 // The algorithm is to:
4642 // - break the vector into scalars
4643 // - apply the operation to each scalar
4644 // - make a vector out the scalar results
4645
4646 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004647 int numComponents = builder.getNumComponents(operands[0]);
4648 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004649 std::vector<spv::Id> results;
4650
4651 // do each scalar op
4652 for (int comp = 0; comp < numComponents; ++comp) {
4653 std::vector<unsigned int> indexes;
4654 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004655 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004656 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004657 if (op == spv::OpSubgroupReadInvocationKHR) {
4658 spvGroupOperands.push_back(scalar);
4659 spvGroupOperands.push_back(operands[1]);
4660 } else if (op == spv::OpGroupBroadcast) {
4661 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004662 spvGroupOperands.push_back(scalar);
4663 spvGroupOperands.push_back(operands[1]);
4664 } else {
chaocf200da82016-12-20 12:44:35 -08004665 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004666 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004667 spvGroupOperands.push_back(scalar);
4668 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004669
Rex Xub7072052016-09-26 15:53:40 +08004670 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004671 }
4672
4673 // put the pieces together
4674 return builder.createCompositeConstruct(typeId, results);
4675}
Rex Xu2bbbe062016-08-23 15:41:05 +08004676
John Kessenich5e4b1242015-08-06 22:53:06 -06004677spv::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 -06004678{
Rex Xu8ff43de2016-04-22 16:51:45 +08004679 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004680#ifdef AMD_EXTENSIONS
4681 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4682#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004683 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004684#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004685
John Kessenich140f3df2015-06-26 16:58:36 -06004686 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004687 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004688 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004689 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004690 spv::Id typeId0 = 0;
4691 if (consumedOperands > 0)
4692 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08004693 spv::Id typeId1 = 0;
4694 if (consumedOperands > 1)
4695 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07004696 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004697
4698 switch (op) {
4699 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004700 if (isFloat)
4701 libCall = spv::GLSLstd450FMin;
4702 else if (isUnsigned)
4703 libCall = spv::GLSLstd450UMin;
4704 else
4705 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004706 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004707 break;
4708 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004709 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004710 break;
4711 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004712 if (isFloat)
4713 libCall = spv::GLSLstd450FMax;
4714 else if (isUnsigned)
4715 libCall = spv::GLSLstd450UMax;
4716 else
4717 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004718 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004719 break;
4720 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004721 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004722 break;
4723 case glslang::EOpDot:
4724 opCode = spv::OpDot;
4725 break;
4726 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004727 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004728 break;
4729
4730 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004731 if (isFloat)
4732 libCall = spv::GLSLstd450FClamp;
4733 else if (isUnsigned)
4734 libCall = spv::GLSLstd450UClamp;
4735 else
4736 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004737 builder.promoteScalar(precision, operands.front(), operands[1]);
4738 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004739 break;
4740 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004741 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4742 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004743 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004744 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004745 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004746 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004747 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004748 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004749 break;
4750 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004751 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004752 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004753 break;
4754 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004755 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004756 builder.promoteScalar(precision, operands[0], operands[2]);
4757 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004758 break;
4759
4760 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004761 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004762 break;
4763 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004764 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004765 break;
4766 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004767 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004768 break;
4769 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004770 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004771 break;
4772 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004773 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004774 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004775 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004776 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004777 libCall = spv::GLSLstd450InterpolateAtSample;
4778 break;
4779 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004780 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004781 libCall = spv::GLSLstd450InterpolateAtOffset;
4782 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004783 case glslang::EOpAddCarry:
4784 opCode = spv::OpIAddCarry;
4785 typeId = builder.makeStructResultType(typeId0, typeId0);
4786 consumedOperands = 2;
4787 break;
4788 case glslang::EOpSubBorrow:
4789 opCode = spv::OpISubBorrow;
4790 typeId = builder.makeStructResultType(typeId0, typeId0);
4791 consumedOperands = 2;
4792 break;
4793 case glslang::EOpUMulExtended:
4794 opCode = spv::OpUMulExtended;
4795 typeId = builder.makeStructResultType(typeId0, typeId0);
4796 consumedOperands = 2;
4797 break;
4798 case glslang::EOpIMulExtended:
4799 opCode = spv::OpSMulExtended;
4800 typeId = builder.makeStructResultType(typeId0, typeId0);
4801 consumedOperands = 2;
4802 break;
4803 case glslang::EOpBitfieldExtract:
4804 if (isUnsigned)
4805 opCode = spv::OpBitFieldUExtract;
4806 else
4807 opCode = spv::OpBitFieldSExtract;
4808 break;
4809 case glslang::EOpBitfieldInsert:
4810 opCode = spv::OpBitFieldInsert;
4811 break;
4812
4813 case glslang::EOpFma:
4814 libCall = spv::GLSLstd450Fma;
4815 break;
4816 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004817 {
4818 libCall = spv::GLSLstd450FrexpStruct;
4819 assert(builder.isPointerType(typeId1));
4820 typeId1 = builder.getContainedTypeId(typeId1);
4821#ifdef AMD_EXTENSIONS
4822 int width = builder.getScalarTypeWidth(typeId1);
4823#else
4824 int width = 32;
4825#endif
4826 if (builder.getNumComponents(operands[0]) == 1)
4827 frexpIntType = builder.makeIntegerType(width, true);
4828 else
4829 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
4830 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4831 consumedOperands = 1;
4832 }
John Kessenich55e7d112015-11-15 21:33:39 -07004833 break;
4834 case glslang::EOpLdexp:
4835 libCall = spv::GLSLstd450Ldexp;
4836 break;
4837
Rex Xu574ab042016-04-14 16:53:07 +08004838 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004839 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004840
Rex Xu9d93a232016-05-05 12:30:44 +08004841#ifdef AMD_EXTENSIONS
4842 case glslang::EOpSwizzleInvocations:
4843 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4844 libCall = spv::SwizzleInvocationsAMD;
4845 break;
4846 case glslang::EOpSwizzleInvocationsMasked:
4847 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4848 libCall = spv::SwizzleInvocationsMaskedAMD;
4849 break;
4850 case glslang::EOpWriteInvocation:
4851 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4852 libCall = spv::WriteInvocationAMD;
4853 break;
4854
4855 case glslang::EOpMin3:
4856 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4857 if (isFloat)
4858 libCall = spv::FMin3AMD;
4859 else {
4860 if (isUnsigned)
4861 libCall = spv::UMin3AMD;
4862 else
4863 libCall = spv::SMin3AMD;
4864 }
4865 break;
4866 case glslang::EOpMax3:
4867 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4868 if (isFloat)
4869 libCall = spv::FMax3AMD;
4870 else {
4871 if (isUnsigned)
4872 libCall = spv::UMax3AMD;
4873 else
4874 libCall = spv::SMax3AMD;
4875 }
4876 break;
4877 case glslang::EOpMid3:
4878 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4879 if (isFloat)
4880 libCall = spv::FMid3AMD;
4881 else {
4882 if (isUnsigned)
4883 libCall = spv::UMid3AMD;
4884 else
4885 libCall = spv::SMid3AMD;
4886 }
4887 break;
4888
4889 case glslang::EOpInterpolateAtVertex:
4890 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4891 libCall = spv::InterpolateAtVertexAMD;
4892 break;
4893#endif
4894
John Kessenich140f3df2015-06-26 16:58:36 -06004895 default:
4896 return 0;
4897 }
4898
4899 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004900 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004901 // Use an extended instruction from the standard library.
4902 // Construct the call arguments, without modifying the original operands vector.
4903 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4904 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004905 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004906 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004907 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004908 case 0:
4909 // should all be handled by visitAggregate and createNoArgOperation
4910 assert(0);
4911 return 0;
4912 case 1:
4913 // should all be handled by createUnaryOperation
4914 assert(0);
4915 return 0;
4916 case 2:
4917 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4918 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004919 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004920 // anything 3 or over doesn't have l-value operands, so all should be consumed
4921 assert(consumedOperands == operands.size());
4922 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004923 break;
4924 }
4925 }
4926
John Kessenich55e7d112015-11-15 21:33:39 -07004927 // Decode the return types that were structures
4928 switch (op) {
4929 case glslang::EOpAddCarry:
4930 case glslang::EOpSubBorrow:
4931 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4932 id = builder.createCompositeExtract(id, typeId0, 0);
4933 break;
4934 case glslang::EOpUMulExtended:
4935 case glslang::EOpIMulExtended:
4936 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4937 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4938 break;
4939 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004940 {
4941 assert(operands.size() == 2);
4942 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
4943 // "exp" is floating-point type (from HLSL intrinsic)
4944 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
4945 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
4946 builder.createStore(member1, operands[1]);
4947 } else
4948 // "exp" is integer type (from GLSL built-in function)
4949 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4950 id = builder.createCompositeExtract(id, typeId0, 0);
4951 }
John Kessenich55e7d112015-11-15 21:33:39 -07004952 break;
4953 default:
4954 break;
4955 }
4956
John Kessenich32cfd492016-02-02 12:37:46 -07004957 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004958}
4959
Rex Xu9d93a232016-05-05 12:30:44 +08004960// Intrinsics with no arguments (or no return value, and no precision).
4961spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004962{
4963 // TODO: get the barrier operands correct
4964
4965 switch (op) {
4966 case glslang::EOpEmitVertex:
4967 builder.createNoResultOp(spv::OpEmitVertex);
4968 return 0;
4969 case glslang::EOpEndPrimitive:
4970 builder.createNoResultOp(spv::OpEndPrimitive);
4971 return 0;
4972 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004973 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004974 return 0;
4975 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004976 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004977 return 0;
4978 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004979 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004980 return 0;
4981 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004982 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004983 return 0;
4984 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004985 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004986 return 0;
4987 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004988 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004989 return 0;
4990 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004991 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004992 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004993 case glslang::EOpAllMemoryBarrierWithGroupSync:
4994 // Control barrier with non-"None" semantic is also a memory barrier.
4995 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4996 return 0;
4997 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4998 // Control barrier with non-"None" semantic is also a memory barrier.
4999 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5000 return 0;
5001 case glslang::EOpWorkgroupMemoryBarrier:
5002 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5003 return 0;
5004 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5005 // Control barrier with non-"None" semantic is also a memory barrier.
5006 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5007 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005008#ifdef AMD_EXTENSIONS
5009 case glslang::EOpTime:
5010 {
5011 std::vector<spv::Id> args; // Dummy arguments
5012 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5013 return builder.setPrecision(id, precision);
5014 }
5015#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005016 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005017 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005018 return 0;
5019 }
5020}
5021
5022spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5023{
John Kessenich2f273362015-07-18 22:34:27 -06005024 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005025 spv::Id id;
5026 if (symbolValues.end() != iter) {
5027 id = iter->second;
5028 return id;
5029 }
5030
5031 // it was not found, create it
5032 id = createSpvVariable(symbol);
5033 symbolValues[symbol->getId()] = id;
5034
Rex Xuc884b4a2016-06-29 15:03:44 +08005035 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005036 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005037 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005038 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005039 if (symbol->getType().getQualifier().hasSpecConstantId())
5040 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005041 if (symbol->getQualifier().hasIndex())
5042 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5043 if (symbol->getQualifier().hasComponent())
5044 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5045 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005046 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005047 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005048 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005049 if (symbol->getQualifier().hasXfbBuffer())
5050 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5051 if (symbol->getQualifier().hasXfbOffset())
5052 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5053 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005054 // atomic counters use this:
5055 if (symbol->getQualifier().hasOffset())
5056 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005057 }
5058
scygan2c864272016-05-18 18:09:17 +02005059 if (symbol->getQualifier().hasLocation())
5060 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005061 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005062 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005063 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005064 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005065 }
John Kessenich140f3df2015-06-26 16:58:36 -06005066 if (symbol->getQualifier().hasSet())
5067 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005068 else if (IsDescriptorResource(symbol->getType())) {
5069 // default to 0
5070 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5071 }
John Kessenich140f3df2015-06-26 16:58:36 -06005072 if (symbol->getQualifier().hasBinding())
5073 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005074 if (symbol->getQualifier().hasAttachment())
5075 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005076 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005077 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005078 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005079 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005080 if (symbol->getQualifier().hasXfbBuffer())
5081 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5082 }
5083
Rex Xu1da878f2016-02-21 20:59:01 +08005084 if (symbol->getType().isImage()) {
5085 std::vector<spv::Decoration> memory;
5086 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5087 for (unsigned int i = 0; i < memory.size(); ++i)
5088 addDecoration(id, memory[i]);
5089 }
5090
John Kessenich140f3df2015-06-26 16:58:36 -06005091 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005092 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005093 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005094 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005095
John Kessenichecba76f2017-01-06 00:34:48 -07005096#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005097 if (builtIn == spv::BuiltInSampleMask) {
5098 spv::Decoration decoration;
5099 // GL_NV_sample_mask_override_coverage extension
5100 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005101 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005102 else
5103 decoration = (spv::Decoration)spv::DecorationMax;
5104 addDecoration(id, decoration);
5105 if (decoration != spv::DecorationMax) {
5106 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5107 }
5108 }
chaoc771d89f2017-01-13 01:10:53 -08005109 else if (builtIn == spv::BuiltInLayer) {
5110 // SPV_NV_viewport_array2 extension
5111 if (symbol->getQualifier().layoutViewportRelative)
5112 {
5113 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5114 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5115 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5116 }
5117 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5118 {
5119 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5120 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5121 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5122 }
5123 }
5124
chaoc6e5acae2016-12-20 13:28:52 -08005125 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005126 addDecoration(id, spv::DecorationPassthroughNV);
5127 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005128 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5129 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005130#endif
5131
John Kessenich140f3df2015-06-26 16:58:36 -06005132 return id;
5133}
5134
John Kessenich55e7d112015-11-15 21:33:39 -07005135// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005136void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5137{
John Kessenich4016e382016-07-15 11:53:56 -06005138 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005139 builder.addDecoration(id, dec);
5140}
5141
John Kessenich55e7d112015-11-15 21:33:39 -07005142// If 'dec' is valid, add a one-operand decoration to an object
5143void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5144{
John Kessenich4016e382016-07-15 11:53:56 -06005145 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005146 builder.addDecoration(id, dec, value);
5147}
5148
5149// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005150void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5151{
John Kessenich4016e382016-07-15 11:53:56 -06005152 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005153 builder.addMemberDecoration(id, (unsigned)member, dec);
5154}
5155
John Kessenich92187592016-02-01 13:45:25 -07005156// If 'dec' is valid, add a one-operand decoration to a struct member
5157void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5158{
John Kessenich4016e382016-07-15 11:53:56 -06005159 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005160 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5161}
5162
John Kessenich55e7d112015-11-15 21:33:39 -07005163// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005164// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005165//
5166// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5167//
5168// Recursively walk the nodes. The nodes form a tree whose leaves are
5169// regular constants, which themselves are trees that createSpvConstant()
5170// recursively walks. So, this function walks the "top" of the tree:
5171// - emit specialization constant-building instructions for specConstant
5172// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005173spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005174{
John Kessenich7cc0e282016-03-20 00:46:02 -06005175 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005176
qining4f4bb812016-04-03 23:55:17 -04005177 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005178 if (! node.getQualifier().specConstant) {
5179 // hand off to the non-spec-constant path
5180 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5181 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005182 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005183 nextConst, false);
5184 }
5185
5186 // We now know we have a specialization constant to build
5187
John Kessenichd94c0032016-05-30 19:29:40 -06005188 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005189 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5190 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5191 std::vector<spv::Id> dimConstId;
5192 for (int dim = 0; dim < 3; ++dim) {
5193 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5194 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5195 if (specConst)
5196 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5197 }
5198 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5199 }
5200
5201 // An AST node labelled as specialization constant should be a symbol node.
5202 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5203 if (auto* sn = node.getAsSymbolNode()) {
5204 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005205 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5206 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5207 // will set the builder into spec constant op instruction generating mode.
5208 sub_tree->traverse(this);
5209 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005210 } else if (auto* const_union_array = &sn->getConstArray()){
5211 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005212 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5213 builder.addName(id, sn->getName().c_str());
5214 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005215 }
5216 }
qining4f4bb812016-04-03 23:55:17 -04005217
5218 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5219 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005220 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005221 exit(1);
5222 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005223}
5224
John Kessenich140f3df2015-06-26 16:58:36 -06005225// Use 'consts' as the flattened glslang source of scalar constants to recursively
5226// build the aggregate SPIR-V constant.
5227//
5228// If there are not enough elements present in 'consts', 0 will be substituted;
5229// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5230//
qining08408382016-03-21 09:51:37 -04005231spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005232{
5233 // vector of constants for SPIR-V
5234 std::vector<spv::Id> spvConsts;
5235
5236 // Type is used for struct and array constants
5237 spv::Id typeId = convertGlslangToSpvType(glslangType);
5238
5239 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005240 glslang::TType elementType(glslangType, 0);
5241 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005242 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005243 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005244 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005245 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005246 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005247 } else if (glslangType.getStruct()) {
5248 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5249 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005250 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005251 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005252 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5253 bool zero = nextConst >= consts.size();
5254 switch (glslangType.getBasicType()) {
5255 case glslang::EbtInt:
5256 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5257 break;
5258 case glslang::EbtUint:
5259 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5260 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005261 case glslang::EbtInt64:
5262 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5263 break;
5264 case glslang::EbtUint64:
5265 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5266 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005267 case glslang::EbtFloat:
5268 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5269 break;
5270 case glslang::EbtDouble:
5271 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5272 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005273#ifdef AMD_EXTENSIONS
5274 case glslang::EbtFloat16:
5275 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5276 break;
5277#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005278 case glslang::EbtBool:
5279 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5280 break;
5281 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005282 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005283 break;
5284 }
5285 ++nextConst;
5286 }
5287 } else {
5288 // we have a non-aggregate (scalar) constant
5289 bool zero = nextConst >= consts.size();
5290 spv::Id scalar = 0;
5291 switch (glslangType.getBasicType()) {
5292 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005293 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005294 break;
5295 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005296 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005297 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005298 case glslang::EbtInt64:
5299 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5300 break;
5301 case glslang::EbtUint64:
5302 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5303 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005304 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005305 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005306 break;
5307 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005308 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005309 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005310#ifdef AMD_EXTENSIONS
5311 case glslang::EbtFloat16:
5312 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5313 break;
5314#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005315 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005316 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005317 break;
5318 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005319 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005320 break;
5321 }
5322 ++nextConst;
5323 return scalar;
5324 }
5325
5326 return builder.makeCompositeConstant(typeId, spvConsts);
5327}
5328
John Kessenich7c1aa102015-10-15 13:29:11 -06005329// Return true if the node is a constant or symbol whose reading has no
5330// non-trivial observable cost or effect.
5331bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5332{
5333 // don't know what this is
5334 if (node == nullptr)
5335 return false;
5336
5337 // a constant is safe
5338 if (node->getAsConstantUnion() != nullptr)
5339 return true;
5340
5341 // not a symbol means non-trivial
5342 if (node->getAsSymbolNode() == nullptr)
5343 return false;
5344
5345 // a symbol, depends on what's being read
5346 switch (node->getType().getQualifier().storage) {
5347 case glslang::EvqTemporary:
5348 case glslang::EvqGlobal:
5349 case glslang::EvqIn:
5350 case glslang::EvqInOut:
5351 case glslang::EvqConst:
5352 case glslang::EvqConstReadOnly:
5353 case glslang::EvqUniform:
5354 return true;
5355 default:
5356 return false;
5357 }
qining25262b32016-05-06 17:25:16 -04005358}
John Kessenich7c1aa102015-10-15 13:29:11 -06005359
5360// A node is trivial if it is a single operation with no side effects.
John Kessenich0d2b4712017-05-19 20:19:00 -06005361// Vector results seem ill-defined, currently classifying them as trivial too,
5362// to avoid scalar bool-based control-flow logic.
5363// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005364// Return true if trivial.
5365bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5366{
5367 if (node == nullptr)
5368 return false;
5369
John Kessenich0d2b4712017-05-19 20:19:00 -06005370 // count vectors as trivial
5371 if (node->getType().isVector())
5372 return true;
5373
John Kessenich7c1aa102015-10-15 13:29:11 -06005374 // symbols and constants are trivial
5375 if (isTrivialLeaf(node))
5376 return true;
5377
5378 // otherwise, it needs to be a simple operation or one or two leaf nodes
5379
5380 // not a simple operation
5381 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5382 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5383 if (binaryNode == nullptr && unaryNode == nullptr)
5384 return false;
5385
5386 // not on leaf nodes
5387 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5388 return false;
5389
5390 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5391 return false;
5392 }
5393
5394 switch (node->getAsOperator()->getOp()) {
5395 case glslang::EOpLogicalNot:
5396 case glslang::EOpConvIntToBool:
5397 case glslang::EOpConvUintToBool:
5398 case glslang::EOpConvFloatToBool:
5399 case glslang::EOpConvDoubleToBool:
5400 case glslang::EOpEqual:
5401 case glslang::EOpNotEqual:
5402 case glslang::EOpLessThan:
5403 case glslang::EOpGreaterThan:
5404 case glslang::EOpLessThanEqual:
5405 case glslang::EOpGreaterThanEqual:
5406 case glslang::EOpIndexDirect:
5407 case glslang::EOpIndexDirectStruct:
5408 case glslang::EOpLogicalXor:
5409 case glslang::EOpAny:
5410 case glslang::EOpAll:
5411 return true;
5412 default:
5413 return false;
5414 }
5415}
5416
5417// Emit short-circuiting code, where 'right' is never evaluated unless
5418// the left side is true (for &&) or false (for ||).
5419spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5420{
5421 spv::Id boolTypeId = builder.makeBoolType();
5422
5423 // emit left operand
5424 builder.clearAccessChain();
5425 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005426 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005427
5428 // Operands to accumulate OpPhi operands
5429 std::vector<spv::Id> phiOperands;
5430 // accumulate left operand's phi information
5431 phiOperands.push_back(leftId);
5432 phiOperands.push_back(builder.getBuildPoint()->getId());
5433
5434 // Make the two kinds of operation symmetric with a "!"
5435 // || => emit "if (! left) result = right"
5436 // && => emit "if ( left) result = right"
5437 //
5438 // TODO: this runtime "not" for || could be avoided by adding functionality
5439 // to 'builder' to have an "else" without an "then"
5440 if (op == glslang::EOpLogicalOr)
5441 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5442
5443 // make an "if" based on the left value
5444 spv::Builder::If ifBuilder(leftId, builder);
5445
5446 // emit right operand as the "then" part of the "if"
5447 builder.clearAccessChain();
5448 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005449 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005450
5451 // accumulate left operand's phi information
5452 phiOperands.push_back(rightId);
5453 phiOperands.push_back(builder.getBuildPoint()->getId());
5454
5455 // finish the "if"
5456 ifBuilder.makeEndIf();
5457
5458 // phi together the two results
5459 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5460}
5461
Rex Xu9d93a232016-05-05 12:30:44 +08005462// Return type Id of the imported set of extended instructions corresponds to the name.
5463// Import this set if it has not been imported yet.
5464spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5465{
5466 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5467 return extBuiltinMap[name];
5468 else {
Rex Xu51596642016-09-21 18:56:12 +08005469 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005470 spv::Id extBuiltins = builder.import(name);
5471 extBuiltinMap[name] = extBuiltins;
5472 return extBuiltins;
5473 }
5474}
5475
John Kessenich140f3df2015-06-26 16:58:36 -06005476}; // end anonymous namespace
5477
5478namespace glslang {
5479
John Kessenich68d78fd2015-07-12 19:28:10 -06005480void GetSpirvVersion(std::string& version)
5481{
John Kessenich9e55f632015-07-15 10:03:39 -06005482 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005483 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005484 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005485 version = buf;
5486}
5487
John Kessenich140f3df2015-06-26 16:58:36 -06005488// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005489void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005490{
5491 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005492 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005493 if (out.fail())
5494 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005495 for (int i = 0; i < (int)spirv.size(); ++i) {
5496 unsigned int word = spirv[i];
5497 out.write((const char*)&word, 4);
5498 }
5499 out.close();
5500}
5501
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005502// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005503void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005504{
5505 std::ofstream out;
5506 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005507 if (out.fail())
5508 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005509 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005510 if (varName != nullptr) {
5511 out << "\t #pragma once" << std::endl;
5512 out << "const uint32_t " << varName << "[] = {" << std::endl;
5513 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005514 const int WORDS_PER_LINE = 8;
5515 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5516 out << "\t";
5517 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5518 const unsigned int word = spirv[i + j];
5519 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5520 if (i + j + 1 < (int)spirv.size()) {
5521 out << ",";
5522 }
5523 }
5524 out << std::endl;
5525 }
Flavio15017db2017-02-15 14:29:33 -08005526 if (varName != nullptr) {
5527 out << "};";
5528 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005529 out.close();
5530}
5531
John Kessenich140f3df2015-06-26 16:58:36 -06005532//
5533// Set up the glslang traversal
5534//
5535void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5536{
Lei Zhang17535f72016-05-04 15:55:59 -04005537 spv::SpvBuildLogger logger;
5538 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005539}
5540
Lei Zhang17535f72016-05-04 15:55:59 -04005541void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005542{
John Kessenich140f3df2015-06-26 16:58:36 -06005543 TIntermNode* root = intermediate.getTreeRoot();
5544
5545 if (root == 0)
5546 return;
5547
5548 glslang::GetThreadPoolAllocator().push();
5549
Lei Zhang17535f72016-05-04 15:55:59 -04005550 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005551 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005552 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005553 it.dumpSpv(spirv);
5554
5555 glslang::GetThreadPoolAllocator().pop();
5556}
5557
5558}; // end namespace glslang