blob: 66ea41a384e2c7761263f303795073d89964701b [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
GregFcd1f1692017-09-21 18:40:22 -060055#ifdef ENABLE_OPT
56 #include "spirv-tools/optimizer.hpp"
57 #include "message.h"
58 #include "SPVRemapper.h"
59#endif
60
61#ifdef ENABLE_OPT
62using namespace spvtools;
63#endif
64
John Kessenich140f3df2015-06-26 16:58:36 -060065// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020066#include "../glslang/MachineIndependent/localintermediate.h"
67#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060068#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050069#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060070
John Kessenich140f3df2015-06-26 16:58:36 -060071#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050072#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040073#include <list>
74#include <map>
75#include <stack>
76#include <string>
77#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060078
79namespace {
80
qining4c912612016-04-01 10:35:16 -040081namespace {
82class SpecConstantOpModeGuard {
83public:
84 SpecConstantOpModeGuard(spv::Builder* builder)
85 : builder_(builder) {
86 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040087 }
88 ~SpecConstantOpModeGuard() {
89 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
90 : builder_->setToNormalCodeGenMode();
91 }
qining40887662016-04-03 22:20:42 -040092 void turnOnSpecConstantOpMode() {
93 builder_->setToSpecConstCodeGenMode();
94 }
qining4c912612016-04-01 10:35:16 -040095
96private:
97 spv::Builder* builder_;
98 bool previous_flag_;
99};
100}
101
John Kessenich140f3df2015-06-26 16:58:36 -0600102//
103// The main holder of information for translating glslang to SPIR-V.
104//
105// Derives from the AST walking base class.
106//
107class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
108public:
John Kessenich121853f2017-05-31 17:11:16 -0600109 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger, glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700110 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600111
112 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
113 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
114 void visitConstantUnion(glslang::TIntermConstantUnion*);
115 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
116 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
117 void visitSymbol(glslang::TIntermSymbol* symbol);
118 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
119 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
120 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
121
John Kessenichfca82622016-11-26 13:23:20 -0700122 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700123 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600124
125protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800126 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800127 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100128 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700129 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
Rex Xu57e65922017-07-04 23:23:40 +0800130 spv::SelectionControlMask TranslateSelectionControl(glslang::TSelectionControl) const;
steve-lunargf1709e72017-05-02 20:14:50 -0600131 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600132 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600133 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
134 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600135 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
136 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
137 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600138 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700139 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600140 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600141 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
142 glslang::TLayoutPacking, const glslang::TQualifier&);
143 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
144 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700145 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700146 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800147 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600148 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700149 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700150 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
151 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
152 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 +0100153 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600154
John Kessenich6fccb3c2016-09-19 16:01:41 -0600155 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd41993d2017-09-10 15:21:05 -0600156 bool writableParam(glslang::TStorageQualifier);
157 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600158 void makeFunctions(const glslang::TIntermSequence&);
159 void makeGlobalInitializers(const glslang::TIntermSequence&);
160 void visitFunctions(const glslang::TIntermSequence&);
161 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800162 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600163 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
164 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600165 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
166
qining25262b32016-05-06 17:25:16 -0400167 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);
168 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
169 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 +0800170 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 +0800171 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 -0600172 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800173 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 +0800174 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800175 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600176 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 +0800177 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600178 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
179 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700180 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600181 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700182 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400183 spv::Id createSpvConstant(const glslang::TIntermTyped&);
184 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600185 bool isTrivialLeaf(const glslang::TIntermTyped* node);
186 bool isTrivial(const glslang::TIntermTyped* node);
187 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800188 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600189
John Kessenich121853f2017-05-31 17:11:16 -0600190 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600191 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600192 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700193 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600194 int sequenceDepth;
195
Lei Zhang17535f72016-05-04 15:55:59 -0400196 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400197
John Kessenich140f3df2015-06-26 16:58:36 -0600198 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
199 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700200 bool inEntryPoint;
201 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700202 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 -0700203 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600204 const glslang::TIntermediate* glslangIntermediate;
205 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800206 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600207
John Kessenich2f273362015-07-18 22:34:27 -0600208 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600209 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600210 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700211 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600212 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 -0600213 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600214};
215
216//
217// Helper functions for translating glslang representations to SPIR-V enumerants.
218//
219
220// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700221spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600222{
John Kessenich66e2faf2016-03-12 18:34:36 -0700223 switch (source) {
224 case glslang::EShSourceGlsl:
225 switch (profile) {
226 case ENoProfile:
227 case ECoreProfile:
228 case ECompatibilityProfile:
229 return spv::SourceLanguageGLSL;
230 case EEsProfile:
231 return spv::SourceLanguageESSL;
232 default:
233 return spv::SourceLanguageUnknown;
234 }
235 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600236 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600237 default:
238 return spv::SourceLanguageUnknown;
239 }
240}
241
242// Translate glslang language (stage) to SPIR-V execution model.
243spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
244{
245 switch (stage) {
246 case EShLangVertex: return spv::ExecutionModelVertex;
247 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
248 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
249 case EShLangGeometry: return spv::ExecutionModelGeometry;
250 case EShLangFragment: return spv::ExecutionModelFragment;
251 case EShLangCompute: return spv::ExecutionModelGLCompute;
252 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700253 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600254 return spv::ExecutionModelFragment;
255 }
256}
257
John Kessenich140f3df2015-06-26 16:58:36 -0600258// Translate glslang sampler type to SPIR-V dimensionality.
259spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
260{
261 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700262 case glslang::Esd1D: return spv::Dim1D;
263 case glslang::Esd2D: return spv::Dim2D;
264 case glslang::Esd3D: return spv::Dim3D;
265 case glslang::EsdCube: return spv::DimCube;
266 case glslang::EsdRect: return spv::DimRect;
267 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700268 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600269 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700270 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600271 return spv::Dim2D;
272 }
273}
274
John Kessenichf6640762016-08-01 19:44:00 -0600275// Translate glslang precision to SPIR-V precision decorations.
276spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600277{
John Kessenichf6640762016-08-01 19:44:00 -0600278 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700279 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600280 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600281 default:
282 return spv::NoPrecision;
283 }
284}
285
John Kessenichf6640762016-08-01 19:44:00 -0600286// Translate glslang type to SPIR-V precision decorations.
287spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
288{
289 return TranslatePrecisionDecoration(type.getQualifier().precision);
290}
291
John Kessenich140f3df2015-06-26 16:58:36 -0600292// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600293spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600294{
295 if (type.getBasicType() == glslang::EbtBlock) {
296 switch (type.getQualifier().storage) {
297 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600298 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600299 case glslang::EvqVaryingIn: return spv::DecorationBlock;
300 case glslang::EvqVaryingOut: return spv::DecorationBlock;
301 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700302 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600303 break;
304 }
305 }
306
John Kessenich4016e382016-07-15 11:53:56 -0600307 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600308}
309
Rex Xu1da878f2016-02-21 20:59:01 +0800310// Translate glslang type to SPIR-V memory decorations.
311void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
312{
313 if (qualifier.coherent)
314 memory.push_back(spv::DecorationCoherent);
315 if (qualifier.volatil)
316 memory.push_back(spv::DecorationVolatile);
317 if (qualifier.restrict)
318 memory.push_back(spv::DecorationRestrict);
319 if (qualifier.readonly)
320 memory.push_back(spv::DecorationNonWritable);
321 if (qualifier.writeonly)
322 memory.push_back(spv::DecorationNonReadable);
323}
324
John Kessenich140f3df2015-06-26 16:58:36 -0600325// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700326spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600327{
328 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700329 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600330 case glslang::ElmRowMajor:
331 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700332 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600333 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700334 default:
335 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600336 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600337 }
338 } else {
339 switch (type.getBasicType()) {
340 default:
John Kessenich4016e382016-07-15 11:53:56 -0600341 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 break;
343 case glslang::EbtBlock:
344 switch (type.getQualifier().storage) {
345 case glslang::EvqUniform:
346 case glslang::EvqBuffer:
347 switch (type.getQualifier().layoutPacking) {
348 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600349 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
350 default:
John Kessenich4016e382016-07-15 11:53:56 -0600351 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600352 }
353 case glslang::EvqVaryingIn:
354 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700355 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700358 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600359 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600360 }
361 }
362 }
363}
364
365// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600366// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700367// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800368spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600369{
Rex Xubbceed72016-05-21 09:40:44 +0800370 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700371 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600372 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800373 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700374 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700375 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600376 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800377#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800378 else if (qualifier.explicitInterp) {
379 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800380 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800381 }
Rex Xu9d93a232016-05-05 12:30:44 +0800382#endif
Rex Xubbceed72016-05-21 09:40:44 +0800383 else
John Kessenich4016e382016-07-15 11:53:56 -0600384 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800385}
386
387// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600388// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800389// should be applied.
390spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
391{
392 if (qualifier.patch)
393 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700394 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600395 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700396 else if (qualifier.sample) {
397 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600398 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700399 } else
John Kessenich4016e382016-07-15 11:53:56 -0600400 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600401}
402
John Kessenich92187592016-02-01 13:45:25 -0700403// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700404spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600405{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700406 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600407 return spv::DecorationInvariant;
408 else
John Kessenich4016e382016-07-15 11:53:56 -0600409 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600410}
411
qining9220dbb2016-05-04 17:34:38 -0400412// If glslang type is noContraction, return SPIR-V NoContraction decoration.
413spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
414{
415 if (qualifier.noContraction)
416 return spv::DecorationNoContraction;
417 else
John Kessenich4016e382016-07-15 11:53:56 -0600418 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400419}
420
David Netoa901ffe2016-06-08 14:11:40 +0100421// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
422// associated capabilities when required. For some built-in variables, a capability
423// is generated only when using the variable in an executable instruction, but not when
424// just declaring a struct member variable with it. This is true for PointSize,
425// ClipDistance, and CullDistance.
426spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600427{
428 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700429 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600430 // Defer adding the capability until the built-in is actually used.
431 if (! memberDeclaration) {
432 switch (glslangIntermediate->getStage()) {
433 case EShLangGeometry:
434 builder.addCapability(spv::CapabilityGeometryPointSize);
435 break;
436 case EShLangTessControl:
437 case EShLangTessEvaluation:
438 builder.addCapability(spv::CapabilityTessellationPointSize);
439 break;
440 default:
441 break;
442 }
John Kessenich92187592016-02-01 13:45:25 -0700443 }
444 return spv::BuiltInPointSize;
445
John Kessenichebb50532016-05-16 19:22:05 -0600446 // These *Distance capabilities logically belong here, but if the member is declared and
447 // then never used, consumers of SPIR-V prefer the capability not be declared.
448 // They are now generated when used, rather than here when declared.
449 // Potentially, the specification should be more clear what the minimum
450 // use needed is to trigger the capability.
451 //
John Kessenich92187592016-02-01 13:45:25 -0700452 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100453 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800454 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700455 return spv::BuiltInClipDistance;
456
457 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100458 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800459 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700460 return spv::BuiltInCullDistance;
461
462 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600463 builder.addCapability(spv::CapabilityMultiViewport);
464 if (glslangIntermediate->getStage() == EShLangVertex ||
465 glslangIntermediate->getStage() == EShLangTessControl ||
466 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800467
John Kessenichba6a3c22017-09-13 13:22:50 -0600468 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
469 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800470 }
John Kessenich92187592016-02-01 13:45:25 -0700471 return spv::BuiltInViewportIndex;
472
John Kessenich5e801132016-02-15 11:09:46 -0700473 case glslang::EbvSampleId:
474 builder.addCapability(spv::CapabilitySampleRateShading);
475 return spv::BuiltInSampleId;
476
477 case glslang::EbvSamplePosition:
478 builder.addCapability(spv::CapabilitySampleRateShading);
479 return spv::BuiltInSamplePosition;
480
481 case glslang::EbvSampleMask:
482 builder.addCapability(spv::CapabilitySampleRateShading);
483 return spv::BuiltInSampleMask;
484
John Kessenich78a45572016-07-08 14:05:15 -0600485 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600486 builder.addCapability(spv::CapabilityGeometry);
487 if (glslangIntermediate->getStage() == EShLangVertex ||
488 glslangIntermediate->getStage() == EShLangTessControl ||
489 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800490
John Kessenichba6a3c22017-09-13 13:22:50 -0600491 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
492 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800493 }
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
Rex Xu37cdcee2017-06-29 17:46:34 +0800522 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800523 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
524 builder.addCapability(spv::CapabilityStencilExportEXT);
525 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800526
John Kessenich140f3df2015-06-26 16:58:36 -0600527 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600528 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
529 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
530 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
531 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
532 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
533 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
534 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600535 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
536 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
537 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
538 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
539 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
540 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
541 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
542 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800543
Rex Xu574ab042016-04-14 16:53:07 +0800544 case glslang::EbvSubGroupSize:
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::BuiltInSubgroupSize;
548
Rex Xu574ab042016-04-14 16:53:07 +0800549 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800550 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800551 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
552 return spv::BuiltInSubgroupLocalInvocationId;
553
Rex Xu574ab042016-04-14 16:53:07 +0800554 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800555 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
556 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
557 return spv::BuiltInSubgroupEqMaskKHR;
558
Rex Xu574ab042016-04-14 16:53:07 +0800559 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800560 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
561 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
562 return spv::BuiltInSubgroupGeMaskKHR;
563
Rex Xu574ab042016-04-14 16:53:07 +0800564 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800565 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
566 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
567 return spv::BuiltInSubgroupGtMaskKHR;
568
Rex Xu574ab042016-04-14 16:53:07 +0800569 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800570 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
571 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
572 return spv::BuiltInSubgroupLeMaskKHR;
573
Rex Xu574ab042016-04-14 16:53:07 +0800574 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800575 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
576 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
577 return spv::BuiltInSubgroupLtMaskKHR;
578
Rex Xu9d93a232016-05-05 12:30:44 +0800579#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800580 case glslang::EbvBaryCoordNoPersp:
581 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
582 return spv::BuiltInBaryCoordNoPerspAMD;
583
584 case glslang::EbvBaryCoordNoPerspCentroid:
585 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
586 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
587
588 case glslang::EbvBaryCoordNoPerspSample:
589 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
590 return spv::BuiltInBaryCoordNoPerspSampleAMD;
591
592 case glslang::EbvBaryCoordSmooth:
593 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
594 return spv::BuiltInBaryCoordSmoothAMD;
595
596 case glslang::EbvBaryCoordSmoothCentroid:
597 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
598 return spv::BuiltInBaryCoordSmoothCentroidAMD;
599
600 case glslang::EbvBaryCoordSmoothSample:
601 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
602 return spv::BuiltInBaryCoordSmoothSampleAMD;
603
604 case glslang::EbvBaryCoordPullModel:
605 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
606 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800607#endif
chaoc771d89f2017-01-13 01:10:53 -0800608
John Kessenich6c8aaac2017-02-27 01:20:51 -0700609 case glslang::EbvDeviceIndex:
610 builder.addExtension(spv::E_SPV_KHR_device_group);
611 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700612 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700613
614 case glslang::EbvViewIndex:
615 builder.addExtension(spv::E_SPV_KHR_multiview);
616 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700617 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700618
chaoc771d89f2017-01-13 01:10:53 -0800619#ifdef NV_EXTENSIONS
620 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800621 if (!memberDeclaration) {
622 builder.addExtension(spv::E_SPV_NV_viewport_array2);
623 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
624 }
chaoc771d89f2017-01-13 01:10:53 -0800625 return spv::BuiltInViewportMaskNV;
626 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800627 if (!memberDeclaration) {
628 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
629 builder.addCapability(spv::CapabilityShaderStereoViewNV);
630 }
chaoc771d89f2017-01-13 01:10:53 -0800631 return spv::BuiltInSecondaryPositionNV;
632 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800633 if (!memberDeclaration) {
634 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
635 builder.addCapability(spv::CapabilityShaderStereoViewNV);
636 }
chaoc771d89f2017-01-13 01:10:53 -0800637 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800638 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800639 if (!memberDeclaration) {
640 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
641 builder.addCapability(spv::CapabilityPerViewAttributesNV);
642 }
chaocdf3956c2017-02-14 14:52:34 -0800643 return spv::BuiltInPositionPerViewNV;
644 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800645 if (!memberDeclaration) {
646 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
647 builder.addCapability(spv::CapabilityPerViewAttributesNV);
648 }
chaocdf3956c2017-02-14 14:52:34 -0800649 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800650#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800651 default:
652 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600653 }
654}
655
Rex Xufc618912015-09-09 16:42:49 +0800656// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700657spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800658{
659 assert(type.getBasicType() == glslang::EbtSampler);
660
John Kessenich5d0fa972016-02-15 11:57:00 -0700661 // Check for capabilities
662 switch (type.getQualifier().layoutFormat) {
663 case glslang::ElfRg32f:
664 case glslang::ElfRg16f:
665 case glslang::ElfR11fG11fB10f:
666 case glslang::ElfR16f:
667 case glslang::ElfRgba16:
668 case glslang::ElfRgb10A2:
669 case glslang::ElfRg16:
670 case glslang::ElfRg8:
671 case glslang::ElfR16:
672 case glslang::ElfR8:
673 case glslang::ElfRgba16Snorm:
674 case glslang::ElfRg16Snorm:
675 case glslang::ElfRg8Snorm:
676 case glslang::ElfR16Snorm:
677 case glslang::ElfR8Snorm:
678
679 case glslang::ElfRg32i:
680 case glslang::ElfRg16i:
681 case glslang::ElfRg8i:
682 case glslang::ElfR16i:
683 case glslang::ElfR8i:
684
685 case glslang::ElfRgb10a2ui:
686 case glslang::ElfRg32ui:
687 case glslang::ElfRg16ui:
688 case glslang::ElfRg8ui:
689 case glslang::ElfR16ui:
690 case glslang::ElfR8ui:
691 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
692 break;
693
694 default:
695 break;
696 }
697
698 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800699 switch (type.getQualifier().layoutFormat) {
700 case glslang::ElfNone: return spv::ImageFormatUnknown;
701 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
702 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
703 case glslang::ElfR32f: return spv::ImageFormatR32f;
704 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
705 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
706 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
707 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
708 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
709 case glslang::ElfR16f: return spv::ImageFormatR16f;
710 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
711 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
712 case glslang::ElfRg16: return spv::ImageFormatRg16;
713 case glslang::ElfRg8: return spv::ImageFormatRg8;
714 case glslang::ElfR16: return spv::ImageFormatR16;
715 case glslang::ElfR8: return spv::ImageFormatR8;
716 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
717 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
718 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
719 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
720 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
721 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
722 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
723 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
724 case glslang::ElfR32i: return spv::ImageFormatR32i;
725 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
726 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
727 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
728 case glslang::ElfR16i: return spv::ImageFormatR16i;
729 case glslang::ElfR8i: return spv::ImageFormatR8i;
730 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
731 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
732 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
733 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
734 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
735 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
736 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
737 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
738 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
739 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600740 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800741 }
742}
743
Rex Xu57e65922017-07-04 23:23:40 +0800744spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
745{
746 switch (selectionControl) {
747 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
748 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
749 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
750 default: return spv::SelectionControlMaskNone;
751 }
752}
753
steve-lunargf1709e72017-05-02 20:14:50 -0600754spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
755{
756 switch (loopControl) {
757 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
758 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
759 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
760 // TODO: DependencyInfinite
761 // TODO: DependencyLength
762 default: return spv::LoopControlMaskNone;
763 }
764}
765
John Kessenicha5c5fb62017-05-05 05:09:58 -0600766// Translate glslang type to SPIR-V storage class.
767spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
768{
769 if (type.getQualifier().isPipeInput())
770 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600771 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600772 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600773
774 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
775 type.getQualifier().storage == glslang::EvqUniform) {
776 if (type.getBasicType() == glslang::EbtAtomicUint)
777 return spv::StorageClassAtomicCounter;
778 if (type.containsOpaque())
779 return spv::StorageClassUniformConstant;
780 }
781
782 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600783 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
784 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600785 }
786
787 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600788 if (type.getQualifier().layoutPushConstant)
789 return spv::StorageClassPushConstant;
790 if (type.getBasicType() == glslang::EbtBlock)
791 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600792 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600793 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600794
795 switch (type.getQualifier().storage) {
796 case glslang::EvqShared: return spv::StorageClassWorkgroup;
797 case glslang::EvqGlobal: return spv::StorageClassPrivate;
798 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
799 case glslang::EvqTemporary: return spv::StorageClassFunction;
800 default:
801 assert(0);
802 break;
803 }
804
805 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600806}
807
qining25262b32016-05-06 17:25:16 -0400808// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700809// descriptor set.
810bool IsDescriptorResource(const glslang::TType& type)
811{
John Kessenichf7497e22016-03-08 21:36:22 -0700812 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700813 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700814 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700815
816 // non block...
817 // basically samplerXXX/subpass/sampler/texture are all included
818 // if they are the global-scope-class, not the function parameter
819 // (or local, if they ever exist) class.
820 if (type.getBasicType() == glslang::EbtSampler)
821 return type.getQualifier().isUniformOrBuffer();
822
823 // None of the above.
824 return false;
825}
826
John Kesseniche0b6cad2015-12-24 10:30:13 -0700827void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
828{
829 if (child.layoutMatrix == glslang::ElmNone)
830 child.layoutMatrix = parent.layoutMatrix;
831
832 if (parent.invariant)
833 child.invariant = true;
834 if (parent.nopersp)
835 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800836#ifdef AMD_EXTENSIONS
837 if (parent.explicitInterp)
838 child.explicitInterp = true;
839#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700840 if (parent.flat)
841 child.flat = true;
842 if (parent.centroid)
843 child.centroid = true;
844 if (parent.patch)
845 child.patch = true;
846 if (parent.sample)
847 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800848 if (parent.coherent)
849 child.coherent = true;
850 if (parent.volatil)
851 child.volatil = true;
852 if (parent.restrict)
853 child.restrict = true;
854 if (parent.readonly)
855 child.readonly = true;
856 if (parent.writeonly)
857 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700858}
859
John Kessenichf2b7f332016-09-01 17:05:23 -0600860bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700861{
John Kessenich7b9fa252016-01-21 18:56:57 -0700862 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600863 // - struct members might inherit from a struct declaration
864 // (note that non-block structs don't explicitly inherit,
865 // only implicitly, meaning no decoration involved)
866 // - affect decorations on the struct members
867 // (note smooth does not, and expecting something like volatile
868 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700869 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600870 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700871}
872
John Kessenich140f3df2015-06-26 16:58:36 -0600873//
874// Implement the TGlslangToSpvTraverser class.
875//
876
John Kessenich121853f2017-05-31 17:11:16 -0600877TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
878 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
879 : TIntermTraverser(true, false, true),
880 options(options),
881 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600882 sequenceDepth(0), logger(buildLogger),
John Kessenicha372a3e2017-11-02 22:32:14 -0600883 builder((glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700884 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600885 glslangIntermediate(glslangIntermediate)
886{
887 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
888
889 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600890 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
891 glslangIntermediate->getVersion());
892
John Kessenich121853f2017-05-31 17:11:16 -0600893 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600894 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600895 builder.setSourceFile(glslangIntermediate->getSourceFile());
896
897 // Set the source shader's text. If for SPV version 1.0, include
898 // a preamble in comments stating the OpModuleProcessed instructions.
899 // Otherwise, emit those as actual instructions.
900 std::string text;
901 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
902 for (int p = 0; p < (int)processes.size(); ++p) {
903 if (glslangIntermediate->getSpv().spv < 0x00010100) {
904 text.append("// OpModuleProcessed ");
905 text.append(processes[p]);
906 text.append("\n");
907 } else
908 builder.addModuleProcessed(processes[p]);
909 }
910 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
911 text.append("#line 1\n");
912 text.append(glslangIntermediate->getSourceText());
913 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600914 }
John Kessenich140f3df2015-06-26 16:58:36 -0600915 stdBuiltins = builder.import("GLSL.std.450");
916 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600917 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
918 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600919
920 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600921 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
922 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600923 builder.addSourceExtension(it->c_str());
924
925 // Add the top-level modes for this shader.
926
John Kessenich92187592016-02-01 13:45:25 -0700927 if (glslangIntermediate->getXfbMode()) {
928 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600929 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700930 }
John Kessenich140f3df2015-06-26 16:58:36 -0600931
932 unsigned int mode;
933 switch (glslangIntermediate->getStage()) {
934 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600935 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600936 break;
937
steve-lunarge7412492017-03-23 11:56:07 -0600938 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600939 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600940 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600941
steve-lunarge7412492017-03-23 11:56:07 -0600942 glslang::TLayoutGeometry primitive;
943
944 if (glslangIntermediate->getStage() == EShLangTessControl) {
945 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
946 primitive = glslangIntermediate->getOutputPrimitive();
947 } else {
948 primitive = glslangIntermediate->getInputPrimitive();
949 }
950
951 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700952 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
953 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
954 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600955 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600956 }
John Kessenich4016e382016-07-15 11:53:56 -0600957 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600958 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
959
John Kesseniche6903322015-10-13 16:29:02 -0600960 switch (glslangIntermediate->getVertexSpacing()) {
961 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
962 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
963 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600964 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600965 }
John Kessenich4016e382016-07-15 11:53:56 -0600966 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600967 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
968
969 switch (glslangIntermediate->getVertexOrder()) {
970 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
971 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600972 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600973 }
John Kessenich4016e382016-07-15 11:53:56 -0600974 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600975 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
976
977 if (glslangIntermediate->getPointMode())
978 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600979 break;
980
981 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600982 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600983 switch (glslangIntermediate->getInputPrimitive()) {
984 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
985 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
986 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700987 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600988 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600989 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600990 }
John Kessenich4016e382016-07-15 11:53:56 -0600991 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600992 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600993
John Kessenich140f3df2015-06-26 16:58:36 -0600994 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
995
996 switch (glslangIntermediate->getOutputPrimitive()) {
997 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
998 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
999 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001000 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001001 }
John Kessenich4016e382016-07-15 11:53:56 -06001002 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001003 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1004 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1005 break;
1006
1007 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001008 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001009 if (glslangIntermediate->getPixelCenterInteger())
1010 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001011
John Kessenich140f3df2015-06-26 16:58:36 -06001012 if (glslangIntermediate->getOriginUpperLeft())
1013 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001014 else
1015 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001016
1017 if (glslangIntermediate->getEarlyFragmentTests())
1018 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1019
chaocc1204522017-06-30 17:14:30 -07001020 if (glslangIntermediate->getPostDepthCoverage()) {
1021 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1022 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1023 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1024 }
1025
John Kesseniche6903322015-10-13 16:29:02 -06001026 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001027 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1028 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001029 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001030 }
John Kessenich4016e382016-07-15 11:53:56 -06001031 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001032 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1033
1034 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1035 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001036 break;
1037
1038 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001039 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001040 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1041 glslangIntermediate->getLocalSize(1),
1042 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001043 break;
1044
1045 default:
1046 break;
1047 }
John Kessenich140f3df2015-06-26 16:58:36 -06001048}
1049
John Kessenichfca82622016-11-26 13:23:20 -07001050// Finish creating SPV, after the traversal is complete.
1051void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001052{
John Kessenich517fe7a2016-11-26 13:31:47 -07001053 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001054 builder.setBuildPoint(shaderEntry->getLastBlock());
1055 builder.leaveFunction();
1056 }
1057
John Kessenich7ba63412015-12-20 17:37:07 -07001058 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001059 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1060 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001061
qiningda397332016-03-09 19:54:03 -05001062 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001063}
1064
John Kessenichfca82622016-11-26 13:23:20 -07001065// Write the SPV into 'out'.
1066void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001067{
John Kessenichfca82622016-11-26 13:23:20 -07001068 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001069}
1070
1071//
1072// Implement the traversal functions.
1073//
1074// Return true from interior nodes to have the external traversal
1075// continue on to children. Return false if children were
1076// already processed.
1077//
1078
1079//
qining25262b32016-05-06 17:25:16 -04001080// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001081// - uniform/input reads
1082// - output writes
1083// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1084// - something simple that degenerates into the last bullet
1085//
1086void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1087{
qining75d1d802016-04-06 14:42:01 -04001088 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1089 if (symbol->getType().getQualifier().isSpecConstant())
1090 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1091
John Kessenich140f3df2015-06-26 16:58:36 -06001092 // getSymbolId() will set up all the IO decorations on the first call.
1093 // Formal function parameters were mapped during makeFunctions().
1094 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001095
1096 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1097 if (builder.isPointer(id)) {
1098 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001099 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1100 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1101 iOSet.insert(id);
1102 }
John Kessenich7ba63412015-12-20 17:37:07 -07001103 }
1104
1105 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001106 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001107 // Prepare to generate code for the access
1108
1109 // L-value chains will be computed left to right. We're on the symbol now,
1110 // which is the left-most part of the access chain, so now is "clear" time,
1111 // followed by setting the base.
1112 builder.clearAccessChain();
1113
1114 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001115 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001116 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001117 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001118 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001119 // These are also pure R-values.
1120 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001121 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001122 builder.setAccessChainRValue(id);
1123 else
1124 builder.setAccessChainLValue(id);
1125 }
1126}
1127
1128bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1129{
John Kesseniche485c7a2017-05-31 18:50:53 -06001130 builder.setLine(node->getLoc().line);
1131
qining40887662016-04-03 22:20:42 -04001132 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1133 if (node->getType().getQualifier().isSpecConstant())
1134 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1135
John Kessenich140f3df2015-06-26 16:58:36 -06001136 // First, handle special cases
1137 switch (node->getOp()) {
1138 case glslang::EOpAssign:
1139 case glslang::EOpAddAssign:
1140 case glslang::EOpSubAssign:
1141 case glslang::EOpMulAssign:
1142 case glslang::EOpVectorTimesMatrixAssign:
1143 case glslang::EOpVectorTimesScalarAssign:
1144 case glslang::EOpMatrixTimesScalarAssign:
1145 case glslang::EOpMatrixTimesMatrixAssign:
1146 case glslang::EOpDivAssign:
1147 case glslang::EOpModAssign:
1148 case glslang::EOpAndAssign:
1149 case glslang::EOpInclusiveOrAssign:
1150 case glslang::EOpExclusiveOrAssign:
1151 case glslang::EOpLeftShiftAssign:
1152 case glslang::EOpRightShiftAssign:
1153 // A bin-op assign "a += b" means the same thing as "a = a + b"
1154 // where a is evaluated before b. For a simple assignment, GLSL
1155 // says to evaluate the left before the right. So, always, left
1156 // node then right node.
1157 {
1158 // get the left l-value, save it away
1159 builder.clearAccessChain();
1160 node->getLeft()->traverse(this);
1161 spv::Builder::AccessChain lValue = builder.getAccessChain();
1162
1163 // evaluate the right
1164 builder.clearAccessChain();
1165 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001166 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001167
1168 if (node->getOp() != glslang::EOpAssign) {
1169 // the left is also an r-value
1170 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001171 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001172
1173 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001174 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001175 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001176 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1177 node->getType().getBasicType());
1178
1179 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001180 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001181 }
1182
1183 // store the result
1184 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001185 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001186
1187 // assignments are expressions having an rValue after they are evaluated...
1188 builder.clearAccessChain();
1189 builder.setAccessChainRValue(rValue);
1190 }
1191 return false;
1192 case glslang::EOpIndexDirect:
1193 case glslang::EOpIndexDirectStruct:
1194 {
1195 // Get the left part of the access chain.
1196 node->getLeft()->traverse(this);
1197
1198 // Add the next element in the chain
1199
David Netoa901ffe2016-06-08 14:11:40 +01001200 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001201 if (! node->getLeft()->getType().isArray() &&
1202 node->getLeft()->getType().isVector() &&
1203 node->getOp() == glslang::EOpIndexDirect) {
1204 // This is essentially a hard-coded vector swizzle of size 1,
1205 // so short circuit the access-chain stuff with a swizzle.
1206 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001207 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001208 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001209 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001210 int spvIndex = glslangIndex;
1211 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1212 node->getOp() == glslang::EOpIndexDirectStruct)
1213 {
1214 // This may be, e.g., an anonymous block-member selection, which generally need
1215 // index remapping due to hidden members in anonymous blocks.
1216 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1217 assert(remapper.size() > 0);
1218 spvIndex = remapper[glslangIndex];
1219 }
John Kessenichebb50532016-05-16 19:22:05 -06001220
David Netoa901ffe2016-06-08 14:11:40 +01001221 // normal case for indexing array or structure or block
1222 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1223
1224 // Add capabilities here for accessing PointSize and clip/cull distance.
1225 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001226 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001227 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001228 }
1229 }
1230 return false;
1231 case glslang::EOpIndexIndirect:
1232 {
1233 // Structure or array or vector indirection.
1234 // Will use native SPIR-V access-chain for struct and array indirection;
1235 // matrices are arrays of vectors, so will also work for a matrix.
1236 // Will use the access chain's 'component' for variable index into a vector.
1237
1238 // This adapter is building access chains left to right.
1239 // Set up the access chain to the left.
1240 node->getLeft()->traverse(this);
1241
1242 // save it so that computing the right side doesn't trash it
1243 spv::Builder::AccessChain partial = builder.getAccessChain();
1244
1245 // compute the next index in the chain
1246 builder.clearAccessChain();
1247 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001248 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001249
1250 // restore the saved access chain
1251 builder.setAccessChain(partial);
1252
1253 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001254 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001255 else
John Kessenichfa668da2015-09-13 14:46:30 -06001256 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001257 }
1258 return false;
1259 case glslang::EOpVectorSwizzle:
1260 {
1261 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001262 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001263 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001264 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001265 }
1266 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001267 case glslang::EOpMatrixSwizzle:
1268 logger->missingFunctionality("matrix swizzle");
1269 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001270 case glslang::EOpLogicalOr:
1271 case glslang::EOpLogicalAnd:
1272 {
1273
1274 // These may require short circuiting, but can sometimes be done as straight
1275 // binary operations. The right operand must be short circuited if it has
1276 // side effects, and should probably be if it is complex.
1277 if (isTrivial(node->getRight()->getAsTyped()))
1278 break; // handle below as a normal binary operation
1279 // otherwise, we need to do dynamic short circuiting on the right operand
1280 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1281 builder.clearAccessChain();
1282 builder.setAccessChainRValue(result);
1283 }
1284 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001285 default:
1286 break;
1287 }
1288
1289 // Assume generic binary op...
1290
John Kessenich32cfd492016-02-02 12:37:46 -07001291 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001292 builder.clearAccessChain();
1293 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001294 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001295
John Kessenich32cfd492016-02-02 12:37:46 -07001296 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001297 builder.clearAccessChain();
1298 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001299 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001300
John Kessenich32cfd492016-02-02 12:37:46 -07001301 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001302 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001303 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001304 convertGlslangToSpvType(node->getType()), left, right,
1305 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001306
John Kessenich50e57562015-12-21 21:21:11 -07001307 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001308 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001309 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001310 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001311 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001312 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001313 return false;
1314 }
John Kessenich140f3df2015-06-26 16:58:36 -06001315}
1316
1317bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1318{
John Kesseniche485c7a2017-05-31 18:50:53 -06001319 builder.setLine(node->getLoc().line);
1320
qining40887662016-04-03 22:20:42 -04001321 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1322 if (node->getType().getQualifier().isSpecConstant())
1323 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1324
John Kessenichfc51d282015-08-19 13:34:18 -06001325 spv::Id result = spv::NoResult;
1326
1327 // try texturing first
1328 result = createImageTextureFunctionCall(node);
1329 if (result != spv::NoResult) {
1330 builder.clearAccessChain();
1331 builder.setAccessChainRValue(result);
1332
1333 return false; // done with this node
1334 }
1335
1336 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001337
1338 if (node->getOp() == glslang::EOpArrayLength) {
1339 // Quite special; won't want to evaluate the operand.
1340
1341 // Normal .length() would have been constant folded by the front-end.
1342 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001343 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001344 assert(node->getOperand()->getType().isRuntimeSizedArray());
1345 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1346 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001347 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1348 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001349
1350 builder.clearAccessChain();
1351 builder.setAccessChainRValue(length);
1352
1353 return false;
1354 }
1355
John Kessenichfc51d282015-08-19 13:34:18 -06001356 // Start by evaluating the operand
1357
John Kessenich8c8505c2016-07-26 12:50:38 -06001358 // Does it need a swizzle inversion? If so, evaluation is inverted;
1359 // operate first on the swizzle base, then apply the swizzle.
1360 spv::Id invertedType = spv::NoType;
1361 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1362 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1363 invertedType = getInvertedSwizzleType(*node->getOperand());
1364
John Kessenich140f3df2015-06-26 16:58:36 -06001365 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001366 if (invertedType != spv::NoType)
1367 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1368 else
1369 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001370
Rex Xufc618912015-09-09 16:42:49 +08001371 spv::Id operand = spv::NoResult;
1372
1373 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1374 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001375 node->getOp() == glslang::EOpAtomicCounter ||
1376 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001377 operand = builder.accessChainGetLValue(); // Special case l-value operands
1378 else
John Kessenich32cfd492016-02-02 12:37:46 -07001379 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001380
John Kessenichf6640762016-08-01 19:44:00 -06001381 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001382 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001383
1384 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001385 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001386 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001387
1388 // if not, then possibly an operation
1389 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001390 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001391
1392 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001393 if (invertedType)
1394 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1395
John Kessenich140f3df2015-06-26 16:58:36 -06001396 builder.clearAccessChain();
1397 builder.setAccessChainRValue(result);
1398
1399 return false; // done with this node
1400 }
1401
1402 // it must be a special case, check...
1403 switch (node->getOp()) {
1404 case glslang::EOpPostIncrement:
1405 case glslang::EOpPostDecrement:
1406 case glslang::EOpPreIncrement:
1407 case glslang::EOpPreDecrement:
1408 {
1409 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001410 spv::Id one = 0;
1411 if (node->getBasicType() == glslang::EbtFloat)
1412 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001413 else if (node->getBasicType() == glslang::EbtDouble)
1414 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001415#ifdef AMD_EXTENSIONS
1416 else if (node->getBasicType() == glslang::EbtFloat16)
1417 one = builder.makeFloat16Constant(1.0F);
1418#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001419 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1420 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001421#ifdef AMD_EXTENSIONS
1422 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1423 one = builder.makeInt16Constant(1);
1424#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001425 else
1426 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001427 glslang::TOperator op;
1428 if (node->getOp() == glslang::EOpPreIncrement ||
1429 node->getOp() == glslang::EOpPostIncrement)
1430 op = glslang::EOpAdd;
1431 else
1432 op = glslang::EOpSub;
1433
John Kessenichf6640762016-08-01 19:44:00 -06001434 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001435 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001436 convertGlslangToSpvType(node->getType()), operand, one,
1437 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001438 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001439
1440 // The result of operation is always stored, but conditionally the
1441 // consumed result. The consumed result is always an r-value.
1442 builder.accessChainStore(result);
1443 builder.clearAccessChain();
1444 if (node->getOp() == glslang::EOpPreIncrement ||
1445 node->getOp() == glslang::EOpPreDecrement)
1446 builder.setAccessChainRValue(result);
1447 else
1448 builder.setAccessChainRValue(operand);
1449 }
1450
1451 return false;
1452
1453 case glslang::EOpEmitStreamVertex:
1454 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1455 return false;
1456 case glslang::EOpEndStreamPrimitive:
1457 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1458 return false;
1459
1460 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001461 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001462 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001463 }
John Kessenich140f3df2015-06-26 16:58:36 -06001464}
1465
1466bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1467{
qining27e04a02016-04-14 16:40:20 -04001468 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1469 if (node->getType().getQualifier().isSpecConstant())
1470 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1471
John Kessenichfc51d282015-08-19 13:34:18 -06001472 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001473 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1474 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001475
1476 // try texturing
1477 result = createImageTextureFunctionCall(node);
1478 if (result != spv::NoResult) {
1479 builder.clearAccessChain();
1480 builder.setAccessChainRValue(result);
1481
1482 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001483#ifdef AMD_EXTENSIONS
1484 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1485#else
John Kessenich56bab042015-09-16 10:54:31 -06001486 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001487#endif
Rex Xufc618912015-09-09 16:42:49 +08001488 // "imageStore" is a special case, which has no result
1489 return false;
1490 }
John Kessenichfc51d282015-08-19 13:34:18 -06001491
John Kessenich140f3df2015-06-26 16:58:36 -06001492 glslang::TOperator binOp = glslang::EOpNull;
1493 bool reduceComparison = true;
1494 bool isMatrix = false;
1495 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001496 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001497
1498 assert(node->getOp());
1499
John Kessenichf6640762016-08-01 19:44:00 -06001500 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001501
1502 switch (node->getOp()) {
1503 case glslang::EOpSequence:
1504 {
1505 if (preVisit)
1506 ++sequenceDepth;
1507 else
1508 --sequenceDepth;
1509
1510 if (sequenceDepth == 1) {
1511 // If this is the parent node of all the functions, we want to see them
1512 // early, so all call points have actual SPIR-V functions to reference.
1513 // In all cases, still let the traverser visit the children for us.
1514 makeFunctions(node->getAsAggregate()->getSequence());
1515
John Kessenich6fccb3c2016-09-19 16:01:41 -06001516 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001517 // anything else gets there, so visit out of order, doing them all now.
1518 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1519
John Kessenich6a60c2f2016-12-08 21:01:59 -07001520 // 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 -06001521 // so do them manually.
1522 visitFunctions(node->getAsAggregate()->getSequence());
1523
1524 return false;
1525 }
1526
1527 return true;
1528 }
1529 case glslang::EOpLinkerObjects:
1530 {
1531 if (visit == glslang::EvPreVisit)
1532 linkageOnly = true;
1533 else
1534 linkageOnly = false;
1535
1536 return true;
1537 }
1538 case glslang::EOpComma:
1539 {
1540 // processing from left to right naturally leaves the right-most
1541 // lying around in the access chain
1542 glslang::TIntermSequence& glslangOperands = node->getSequence();
1543 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1544 glslangOperands[i]->traverse(this);
1545
1546 return false;
1547 }
1548 case glslang::EOpFunction:
1549 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001550 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001551 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001552 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001553 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001554 } else {
1555 handleFunctionEntry(node);
1556 }
1557 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001558 if (inEntryPoint)
1559 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001560 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001561 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001562 }
1563
1564 return true;
1565 case glslang::EOpParameters:
1566 // Parameters will have been consumed by EOpFunction processing, but not
1567 // the body, so we still visited the function node's children, making this
1568 // child redundant.
1569 return false;
1570 case glslang::EOpFunctionCall:
1571 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001572 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001573 if (node->isUserDefined())
1574 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001575 // 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 -07001576 if (result) {
1577 builder.clearAccessChain();
1578 builder.setAccessChainRValue(result);
1579 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001580 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001581
1582 return false;
1583 }
1584 case glslang::EOpConstructMat2x2:
1585 case glslang::EOpConstructMat2x3:
1586 case glslang::EOpConstructMat2x4:
1587 case glslang::EOpConstructMat3x2:
1588 case glslang::EOpConstructMat3x3:
1589 case glslang::EOpConstructMat3x4:
1590 case glslang::EOpConstructMat4x2:
1591 case glslang::EOpConstructMat4x3:
1592 case glslang::EOpConstructMat4x4:
1593 case glslang::EOpConstructDMat2x2:
1594 case glslang::EOpConstructDMat2x3:
1595 case glslang::EOpConstructDMat2x4:
1596 case glslang::EOpConstructDMat3x2:
1597 case glslang::EOpConstructDMat3x3:
1598 case glslang::EOpConstructDMat3x4:
1599 case glslang::EOpConstructDMat4x2:
1600 case glslang::EOpConstructDMat4x3:
1601 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001602 case glslang::EOpConstructIMat2x2:
1603 case glslang::EOpConstructIMat2x3:
1604 case glslang::EOpConstructIMat2x4:
1605 case glslang::EOpConstructIMat3x2:
1606 case glslang::EOpConstructIMat3x3:
1607 case glslang::EOpConstructIMat3x4:
1608 case glslang::EOpConstructIMat4x2:
1609 case glslang::EOpConstructIMat4x3:
1610 case glslang::EOpConstructIMat4x4:
1611 case glslang::EOpConstructUMat2x2:
1612 case glslang::EOpConstructUMat2x3:
1613 case glslang::EOpConstructUMat2x4:
1614 case glslang::EOpConstructUMat3x2:
1615 case glslang::EOpConstructUMat3x3:
1616 case glslang::EOpConstructUMat3x4:
1617 case glslang::EOpConstructUMat4x2:
1618 case glslang::EOpConstructUMat4x3:
1619 case glslang::EOpConstructUMat4x4:
1620 case glslang::EOpConstructBMat2x2:
1621 case glslang::EOpConstructBMat2x3:
1622 case glslang::EOpConstructBMat2x4:
1623 case glslang::EOpConstructBMat3x2:
1624 case glslang::EOpConstructBMat3x3:
1625 case glslang::EOpConstructBMat3x4:
1626 case glslang::EOpConstructBMat4x2:
1627 case glslang::EOpConstructBMat4x3:
1628 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001629#ifdef AMD_EXTENSIONS
1630 case glslang::EOpConstructF16Mat2x2:
1631 case glslang::EOpConstructF16Mat2x3:
1632 case glslang::EOpConstructF16Mat2x4:
1633 case glslang::EOpConstructF16Mat3x2:
1634 case glslang::EOpConstructF16Mat3x3:
1635 case glslang::EOpConstructF16Mat3x4:
1636 case glslang::EOpConstructF16Mat4x2:
1637 case glslang::EOpConstructF16Mat4x3:
1638 case glslang::EOpConstructF16Mat4x4:
1639#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001640 isMatrix = true;
1641 // fall through
1642 case glslang::EOpConstructFloat:
1643 case glslang::EOpConstructVec2:
1644 case glslang::EOpConstructVec3:
1645 case glslang::EOpConstructVec4:
1646 case glslang::EOpConstructDouble:
1647 case glslang::EOpConstructDVec2:
1648 case glslang::EOpConstructDVec3:
1649 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001650#ifdef AMD_EXTENSIONS
1651 case glslang::EOpConstructFloat16:
1652 case glslang::EOpConstructF16Vec2:
1653 case glslang::EOpConstructF16Vec3:
1654 case glslang::EOpConstructF16Vec4:
1655#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001656 case glslang::EOpConstructBool:
1657 case glslang::EOpConstructBVec2:
1658 case glslang::EOpConstructBVec3:
1659 case glslang::EOpConstructBVec4:
1660 case glslang::EOpConstructInt:
1661 case glslang::EOpConstructIVec2:
1662 case glslang::EOpConstructIVec3:
1663 case glslang::EOpConstructIVec4:
1664 case glslang::EOpConstructUint:
1665 case glslang::EOpConstructUVec2:
1666 case glslang::EOpConstructUVec3:
1667 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001668 case glslang::EOpConstructInt64:
1669 case glslang::EOpConstructI64Vec2:
1670 case glslang::EOpConstructI64Vec3:
1671 case glslang::EOpConstructI64Vec4:
1672 case glslang::EOpConstructUint64:
1673 case glslang::EOpConstructU64Vec2:
1674 case glslang::EOpConstructU64Vec3:
1675 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001676#ifdef AMD_EXTENSIONS
1677 case glslang::EOpConstructInt16:
1678 case glslang::EOpConstructI16Vec2:
1679 case glslang::EOpConstructI16Vec3:
1680 case glslang::EOpConstructI16Vec4:
1681 case glslang::EOpConstructUint16:
1682 case glslang::EOpConstructU16Vec2:
1683 case glslang::EOpConstructU16Vec3:
1684 case glslang::EOpConstructU16Vec4:
1685#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001686 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001687 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001688 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001689 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001690 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001691 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001692 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001693 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001694 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001695 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001696 std::vector<spv::Id> constituents;
1697 for (int c = 0; c < (int)arguments.size(); ++c)
1698 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001699 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001700 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001701 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001702 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001703 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001704
1705 builder.clearAccessChain();
1706 builder.setAccessChainRValue(constructed);
1707
1708 return false;
1709 }
1710
1711 // These six are component-wise compares with component-wise results.
1712 // Forward on to createBinaryOperation(), requesting a vector result.
1713 case glslang::EOpLessThan:
1714 case glslang::EOpGreaterThan:
1715 case glslang::EOpLessThanEqual:
1716 case glslang::EOpGreaterThanEqual:
1717 case glslang::EOpVectorEqual:
1718 case glslang::EOpVectorNotEqual:
1719 {
1720 // Map the operation to a binary
1721 binOp = node->getOp();
1722 reduceComparison = false;
1723 switch (node->getOp()) {
1724 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1725 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1726 default: binOp = node->getOp(); break;
1727 }
1728
1729 break;
1730 }
1731 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001732 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001733 binOp = glslang::EOpMul;
1734 break;
1735 case glslang::EOpOuterProduct:
1736 // two vectors multiplied to make a matrix
1737 binOp = glslang::EOpOuterProduct;
1738 break;
1739 case glslang::EOpDot:
1740 {
qining25262b32016-05-06 17:25:16 -04001741 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001742 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001743 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001744 binOp = glslang::EOpMul;
1745 break;
1746 }
1747 case glslang::EOpMod:
1748 // when an aggregate, this is the floating-point mod built-in function,
1749 // which can be emitted by the one in createBinaryOperation()
1750 binOp = glslang::EOpMod;
1751 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001752 case glslang::EOpEmitVertex:
1753 case glslang::EOpEndPrimitive:
1754 case glslang::EOpBarrier:
1755 case glslang::EOpMemoryBarrier:
1756 case glslang::EOpMemoryBarrierAtomicCounter:
1757 case glslang::EOpMemoryBarrierBuffer:
1758 case glslang::EOpMemoryBarrierImage:
1759 case glslang::EOpMemoryBarrierShared:
1760 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001761 case glslang::EOpAllMemoryBarrierWithGroupSync:
1762 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1763 case glslang::EOpWorkgroupMemoryBarrier:
1764 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001765 noReturnValue = true;
1766 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1767 break;
1768
John Kessenich426394d2015-07-23 10:22:48 -06001769 case glslang::EOpAtomicAdd:
1770 case glslang::EOpAtomicMin:
1771 case glslang::EOpAtomicMax:
1772 case glslang::EOpAtomicAnd:
1773 case glslang::EOpAtomicOr:
1774 case glslang::EOpAtomicXor:
1775 case glslang::EOpAtomicExchange:
1776 case glslang::EOpAtomicCompSwap:
1777 atomic = true;
1778 break;
1779
John Kessenich0d0c6d32017-07-23 16:08:26 -06001780 case glslang::EOpAtomicCounterAdd:
1781 case glslang::EOpAtomicCounterSubtract:
1782 case glslang::EOpAtomicCounterMin:
1783 case glslang::EOpAtomicCounterMax:
1784 case glslang::EOpAtomicCounterAnd:
1785 case glslang::EOpAtomicCounterOr:
1786 case glslang::EOpAtomicCounterXor:
1787 case glslang::EOpAtomicCounterExchange:
1788 case glslang::EOpAtomicCounterCompSwap:
1789 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1790 builder.addCapability(spv::CapabilityAtomicStorageOps);
1791 atomic = true;
1792 break;
1793
John Kessenich140f3df2015-06-26 16:58:36 -06001794 default:
1795 break;
1796 }
1797
1798 //
1799 // See if it maps to a regular operation.
1800 //
John Kessenich140f3df2015-06-26 16:58:36 -06001801 if (binOp != glslang::EOpNull) {
1802 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1803 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1804 assert(left && right);
1805
1806 builder.clearAccessChain();
1807 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001808 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001809
1810 builder.clearAccessChain();
1811 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001812 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001813
John Kesseniche485c7a2017-05-31 18:50:53 -06001814 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001815 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001816 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001817 left->getType().getBasicType(), reduceComparison);
1818
1819 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001820 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001821 builder.clearAccessChain();
1822 builder.setAccessChainRValue(result);
1823
1824 return false;
1825 }
1826
John Kessenich426394d2015-07-23 10:22:48 -06001827 //
1828 // Create the list of operands.
1829 //
John Kessenich140f3df2015-06-26 16:58:36 -06001830 glslang::TIntermSequence& glslangOperands = node->getSequence();
1831 std::vector<spv::Id> operands;
1832 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001833 // special case l-value operands; there are just a few
1834 bool lvalue = false;
1835 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001836 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001837 case glslang::EOpModf:
1838 if (arg == 1)
1839 lvalue = true;
1840 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001841 case glslang::EOpInterpolateAtSample:
1842 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001843#ifdef AMD_EXTENSIONS
1844 case glslang::EOpInterpolateAtVertex:
1845#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001846 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001847 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001848
1849 // Does it need a swizzle inversion? If so, evaluation is inverted;
1850 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001851 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001852 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1853 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1854 }
Rex Xu7a26c172015-12-08 17:12:09 +08001855 break;
Rex Xud4782c12015-09-06 16:30:11 +08001856 case glslang::EOpAtomicAdd:
1857 case glslang::EOpAtomicMin:
1858 case glslang::EOpAtomicMax:
1859 case glslang::EOpAtomicAnd:
1860 case glslang::EOpAtomicOr:
1861 case glslang::EOpAtomicXor:
1862 case glslang::EOpAtomicExchange:
1863 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001864 case glslang::EOpAtomicCounterAdd:
1865 case glslang::EOpAtomicCounterSubtract:
1866 case glslang::EOpAtomicCounterMin:
1867 case glslang::EOpAtomicCounterMax:
1868 case glslang::EOpAtomicCounterAnd:
1869 case glslang::EOpAtomicCounterOr:
1870 case glslang::EOpAtomicCounterXor:
1871 case glslang::EOpAtomicCounterExchange:
1872 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001873 if (arg == 0)
1874 lvalue = true;
1875 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001876 case glslang::EOpAddCarry:
1877 case glslang::EOpSubBorrow:
1878 if (arg == 2)
1879 lvalue = true;
1880 break;
1881 case glslang::EOpUMulExtended:
1882 case glslang::EOpIMulExtended:
1883 if (arg >= 2)
1884 lvalue = true;
1885 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001886 default:
1887 break;
1888 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001889 builder.clearAccessChain();
1890 if (invertedType != spv::NoType && arg == 0)
1891 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1892 else
1893 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001894 if (lvalue)
1895 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001896 else {
1897 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001898 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001899 }
John Kessenich140f3df2015-06-26 16:58:36 -06001900 }
John Kessenich426394d2015-07-23 10:22:48 -06001901
John Kesseniche485c7a2017-05-31 18:50:53 -06001902 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001903 if (atomic) {
1904 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001905 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001906 } else {
1907 // Pass through to generic operations.
1908 switch (glslangOperands.size()) {
1909 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001910 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001911 break;
1912 case 1:
qining25262b32016-05-06 17:25:16 -04001913 result = createUnaryOperation(
1914 node->getOp(), precision,
1915 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001916 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001917 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001918 break;
1919 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001920 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001921 break;
1922 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001923 if (invertedType)
1924 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001925 }
1926
1927 if (noReturnValue)
1928 return false;
1929
1930 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001931 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001932 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001933 } else {
1934 builder.clearAccessChain();
1935 builder.setAccessChainRValue(result);
1936 return false;
1937 }
1938}
1939
John Kessenich433e9ff2017-01-26 20:31:11 -07001940// This path handles both if-then-else and ?:
1941// The if-then-else has a node type of void, while
1942// ?: has either a void or a non-void node type
1943//
1944// Leaving the result, when not void:
1945// GLSL only has r-values as the result of a :?, but
1946// if we have an l-value, that can be more efficient if it will
1947// become the base of a complex r-value expression, because the
1948// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001949bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1950{
John Kessenich433e9ff2017-01-26 20:31:11 -07001951 // See if it simple and safe to generate OpSelect instead of using control flow.
1952 // Crucially, side effects must be avoided, and there are performance trade-offs.
1953 // Return true if good idea (and safe) for OpSelect, false otherwise.
1954 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001955 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1956 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001957 return false;
1958
1959 if (node->getTrueBlock() == nullptr ||
1960 node->getFalseBlock() == nullptr)
1961 return false;
1962
1963 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1964 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1965
1966 // return true if a single operand to ? : is okay for OpSelect
1967 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001968 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001969 };
1970
1971 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1972 operandOkay(node->getFalseBlock()->getAsTyped());
1973 };
1974
1975 // Emit OpSelect for this selection.
1976 const auto handleAsOpSelect = [&]() {
1977 node->getCondition()->traverse(this);
1978 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1979 node->getTrueBlock()->traverse(this);
1980 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1981 node->getFalseBlock()->traverse(this);
1982 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1983
John Kesseniche485c7a2017-05-31 18:50:53 -06001984 builder.setLine(node->getLoc().line);
1985
John Kesseniche434ad92017-03-30 10:09:28 -06001986 // smear condition to vector, if necessary (AST is always scalar)
1987 if (builder.isVector(trueValue))
1988 condition = builder.smearScalar(spv::NoPrecision, condition,
1989 builder.makeVectorType(builder.makeBoolType(),
1990 builder.getNumComponents(trueValue)));
1991
1992 spv::Id select = builder.createTriOp(spv::OpSelect,
1993 convertGlslangToSpvType(node->getType()), condition,
1994 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001995 builder.clearAccessChain();
1996 builder.setAccessChainRValue(select);
1997 };
1998
1999 // Try for OpSelect
2000
2001 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002002 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2003 if (node->getType().getQualifier().isSpecConstant())
2004 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2005
John Kessenich433e9ff2017-01-26 20:31:11 -07002006 handleAsOpSelect();
2007 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002008 }
2009
Rex Xu57e65922017-07-04 23:23:40 +08002010 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07002011 // Don't handle results as temporaries, because there will be two names
2012 // and better to leave SSA to later passes.
2013 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
2014 ? spv::NoResult
2015 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2016
John Kessenich140f3df2015-06-26 16:58:36 -06002017 // emit the condition before doing anything with selection
2018 node->getCondition()->traverse(this);
2019
Rex Xu57e65922017-07-04 23:23:40 +08002020 // Selection control:
2021 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2022
John Kessenich140f3df2015-06-26 16:58:36 -06002023 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08002024 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06002025
John Kessenich433e9ff2017-01-26 20:31:11 -07002026 // emit the "then" statement
2027 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002028 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002029 if (result != spv::NoResult)
2030 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002031 }
2032
John Kessenich433e9ff2017-01-26 20:31:11 -07002033 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002034 ifBuilder.makeBeginElse();
2035 // emit the "else" statement
2036 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002037 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002038 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002039 }
2040
John Kessenich433e9ff2017-01-26 20:31:11 -07002041 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002042 ifBuilder.makeEndIf();
2043
John Kessenich433e9ff2017-01-26 20:31:11 -07002044 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002045 // GLSL only has r-values as the result of a :?, but
2046 // if we have an l-value, that can be more efficient if it will
2047 // become the base of a complex r-value expression, because the
2048 // next layer copies r-values into memory to use the access-chain mechanism
2049 builder.clearAccessChain();
2050 builder.setAccessChainLValue(result);
2051 }
2052
2053 return false;
2054}
2055
2056bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2057{
2058 // emit and get the condition before doing anything with switch
2059 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002060 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002061
Rex Xu57e65922017-07-04 23:23:40 +08002062 // Selection control:
2063 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2064
John Kessenich140f3df2015-06-26 16:58:36 -06002065 // browse the children to sort out code segments
2066 int defaultSegment = -1;
2067 std::vector<TIntermNode*> codeSegments;
2068 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2069 std::vector<int> caseValues;
2070 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2071 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2072 TIntermNode* child = *c;
2073 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002074 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002075 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002076 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002077 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2078 } else
2079 codeSegments.push_back(child);
2080 }
2081
qining25262b32016-05-06 17:25:16 -04002082 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002083 // statements between the last case and the end of the switch statement
2084 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2085 (int)codeSegments.size() == defaultSegment)
2086 codeSegments.push_back(nullptr);
2087
2088 // make the switch statement
2089 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002090 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002091
2092 // emit all the code in the segments
2093 breakForLoop.push(false);
2094 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2095 builder.nextSwitchSegment(segmentBlocks, s);
2096 if (codeSegments[s])
2097 codeSegments[s]->traverse(this);
2098 else
2099 builder.addSwitchBreak();
2100 }
2101 breakForLoop.pop();
2102
2103 builder.endSwitch(segmentBlocks);
2104
2105 return false;
2106}
2107
2108void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2109{
2110 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002111 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002112
2113 builder.clearAccessChain();
2114 builder.setAccessChainRValue(constant);
2115}
2116
2117bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2118{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002119 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002120 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002121
2122 // Loop control:
2123 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2124
2125 // TODO: dependency length
2126
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002127 // Spec requires back edges to target header blocks, and every header block
2128 // must dominate its merge block. Make a header block first to ensure these
2129 // conditions are met. By definition, it will contain OpLoopMerge, followed
2130 // by a block-ending branch. But we don't want to put any other body/test
2131 // instructions in it, since the body/test may have arbitrary instructions,
2132 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002133 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002134 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002135 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002136 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002137 spv::Block& test = builder.makeNewBlock();
2138 builder.createBranch(&test);
2139
2140 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002141 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002142 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002143 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2144
2145 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002146 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002147 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002148 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002149 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002150 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002151
2152 builder.setBuildPoint(&blocks.continue_target);
2153 if (node->getTerminal())
2154 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002155 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002156 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002157 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002158 builder.createBranch(&blocks.body);
2159
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002160 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002161 builder.setBuildPoint(&blocks.body);
2162 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002163 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002164 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002165 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002166
2167 builder.setBuildPoint(&blocks.continue_target);
2168 if (node->getTerminal())
2169 node->getTerminal()->traverse(this);
2170 if (node->getTest()) {
2171 node->getTest()->traverse(this);
2172 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002173 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002174 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002175 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002176 // TODO: unless there was a break/return/discard instruction
2177 // somewhere in the body, this is an infinite loop, so we should
2178 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002179 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002180 }
John Kessenich140f3df2015-06-26 16:58:36 -06002181 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002182 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002183 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002184 return false;
2185}
2186
2187bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2188{
2189 if (node->getExpression())
2190 node->getExpression()->traverse(this);
2191
John Kesseniche485c7a2017-05-31 18:50:53 -06002192 builder.setLine(node->getLoc().line);
2193
John Kessenich140f3df2015-06-26 16:58:36 -06002194 switch (node->getFlowOp()) {
2195 case glslang::EOpKill:
2196 builder.makeDiscard();
2197 break;
2198 case glslang::EOpBreak:
2199 if (breakForLoop.top())
2200 builder.createLoopExit();
2201 else
2202 builder.addSwitchBreak();
2203 break;
2204 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002205 builder.createLoopContinue();
2206 break;
2207 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002208 if (node->getExpression()) {
2209 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2210 spv::Id returnId = accessChainLoad(glslangReturnType);
2211 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2212 builder.clearAccessChain();
2213 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2214 builder.setAccessChainLValue(copyId);
2215 multiTypeStore(glslangReturnType, returnId);
2216 returnId = builder.createLoad(copyId);
2217 }
2218 builder.makeReturn(false, returnId);
2219 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002220 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002221
2222 builder.clearAccessChain();
2223 break;
2224
2225 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002226 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002227 break;
2228 }
2229
2230 return false;
2231}
2232
2233spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2234{
qining25262b32016-05-06 17:25:16 -04002235 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002236 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002237 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002238 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002239 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002240 }
2241
2242 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002243 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002244 spv::Id spvType = convertGlslangToSpvType(node->getType());
2245
Rex Xuf89ad982017-04-07 23:22:33 +08002246#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002247 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2248 node->getType().containsBasicType(glslang::EbtInt16) ||
2249 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002250 if (contains16BitType) {
2251 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2252 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2253 builder.addCapability(spv::CapabilityStorageInputOutput16);
2254 } else if (storageClass == spv::StorageClassPushConstant) {
2255 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2256 builder.addCapability(spv::CapabilityStoragePushConstant16);
2257 } else if (storageClass == spv::StorageClassUniform) {
2258 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2259 builder.addCapability(spv::CapabilityStorageUniform16);
2260 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2261 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2262 }
2263 }
2264#endif
2265
John Kessenich140f3df2015-06-26 16:58:36 -06002266 const char* name = node->getName().c_str();
2267 if (glslang::IsAnonymous(name))
2268 name = "";
2269
2270 return builder.createVariable(storageClass, spvType, name);
2271}
2272
2273// Return type Id of the sampled type.
2274spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2275{
2276 switch (sampler.type) {
2277 case glslang::EbtFloat: return builder.makeFloatType(32);
2278 case glslang::EbtInt: return builder.makeIntType(32);
2279 case glslang::EbtUint: return builder.makeUintType(32);
2280 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002281 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002282 return builder.makeFloatType(32);
2283 }
2284}
2285
John Kessenich8c8505c2016-07-26 12:50:38 -06002286// If node is a swizzle operation, return the type that should be used if
2287// the swizzle base is first consumed by another operation, before the swizzle
2288// is applied.
2289spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2290{
John Kessenichecba76f2017-01-06 00:34:48 -07002291 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002292 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2293 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2294 else
2295 return spv::NoType;
2296}
2297
2298// When inverting a swizzle with a parent op, this function
2299// will apply the swizzle operation to a completed parent operation.
2300spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2301{
2302 std::vector<unsigned> swizzle;
2303 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2304 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2305}
2306
John Kessenich8c8505c2016-07-26 12:50:38 -06002307// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2308void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2309{
2310 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2311 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2312 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2313}
2314
John Kessenich3ac051e2015-12-20 11:29:16 -07002315// Convert from a glslang type to an SPV type, by calling into a
2316// recursive version of this function. This establishes the inherited
2317// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002318spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2319{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002320 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002321}
2322
2323// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002324// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002325// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002326spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002327{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002328 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002329
2330 switch (type.getBasicType()) {
2331 case glslang::EbtVoid:
2332 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002333 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002334 break;
2335 case glslang::EbtFloat:
2336 spvType = builder.makeFloatType(32);
2337 break;
2338 case glslang::EbtDouble:
2339 spvType = builder.makeFloatType(64);
2340 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002341#ifdef AMD_EXTENSIONS
2342 case glslang::EbtFloat16:
2343 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002344 spvType = builder.makeFloatType(16);
2345 break;
2346#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002347 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002348 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2349 // a 32-bit int where non-0 means true.
2350 if (explicitLayout != glslang::ElpNone)
2351 spvType = builder.makeUintType(32);
2352 else
2353 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002354 break;
2355 case glslang::EbtInt:
2356 spvType = builder.makeIntType(32);
2357 break;
2358 case glslang::EbtUint:
2359 spvType = builder.makeUintType(32);
2360 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002361 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002362 spvType = builder.makeIntType(64);
2363 break;
2364 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002365 spvType = builder.makeUintType(64);
2366 break;
Rex Xucabbb782017-03-24 13:41:14 +08002367#ifdef AMD_EXTENSIONS
2368 case glslang::EbtInt16:
2369 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2370 spvType = builder.makeIntType(16);
2371 break;
2372 case glslang::EbtUint16:
2373 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2374 spvType = builder.makeUintType(16);
2375 break;
2376#endif
John Kessenich426394d2015-07-23 10:22:48 -06002377 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002378 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002379 spvType = builder.makeUintType(32);
2380 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002381 case glslang::EbtSampler:
2382 {
2383 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002384 if (sampler.sampler) {
2385 // pure sampler
2386 spvType = builder.makeSamplerType();
2387 } else {
2388 // an image is present, make its type
2389 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2390 sampler.image ? 2 : 1, TranslateImageFormat(type));
2391 if (sampler.combined) {
2392 // already has both image and sampler, make the combined type
2393 spvType = builder.makeSampledImageType(spvType);
2394 }
John Kessenich55e7d112015-11-15 21:33:39 -07002395 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002396 }
John Kessenich140f3df2015-06-26 16:58:36 -06002397 break;
2398 case glslang::EbtStruct:
2399 case glslang::EbtBlock:
2400 {
2401 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002402 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002403
2404 // Try to share structs for different layouts, but not yet for other
2405 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002406 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002407 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002408 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002409 break;
2410
2411 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002412 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002413 memberRemapper[glslangMembers].resize(glslangMembers->size());
2414 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002415 }
2416 break;
2417 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002418 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002419 break;
2420 }
2421
2422 if (type.isMatrix())
2423 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2424 else {
2425 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2426 if (type.getVectorSize() > 1)
2427 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2428 }
2429
2430 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002431 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2432
John Kessenichc9a80832015-09-12 12:17:44 -06002433 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002434 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002435 // We need to decorate array strides for types needing explicit layout, except blocks.
2436 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002437 // Use a dummy glslang type for querying internal strides of
2438 // arrays of arrays, but using just a one-dimensional array.
2439 glslang::TType simpleArrayType(type, 0); // deference type of the array
2440 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2441 simpleArrayType.getArraySizes().dereference();
2442
2443 // Will compute the higher-order strides here, rather than making a whole
2444 // pile of types and doing repetitive recursion on their contents.
2445 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2446 }
John Kessenichf8842e52016-01-04 19:22:56 -07002447
2448 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002449 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002450 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002451 if (stride > 0)
2452 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002453 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002454 }
2455 } else {
2456 // single-dimensional array, and don't yet have stride
2457
John Kessenichf8842e52016-01-04 19:22:56 -07002458 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002459 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2460 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002461 }
John Kessenich31ed4832015-09-09 17:51:38 -06002462
John Kessenichc9a80832015-09-12 12:17:44 -06002463 // Do the outer dimension, which might not be known for a runtime-sized array
2464 if (type.isRuntimeSizedArray()) {
2465 spvType = builder.makeRuntimeArray(spvType);
2466 } else {
2467 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002468 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002469 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002470 if (stride > 0)
2471 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002472 }
2473
2474 return spvType;
2475}
2476
John Kessenich0e737842017-03-24 18:38:16 -06002477// TODO: this functionality should exist at a higher level, in creating the AST
2478//
2479// Identify interface members that don't have their required extension turned on.
2480//
2481bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2482{
2483 auto& extensions = glslangIntermediate->getRequestedExtensions();
2484
Rex Xubcf291a2017-03-29 23:01:36 +08002485 if (member.getFieldName() == "gl_ViewportMask" &&
2486 extensions.find("GL_NV_viewport_array2") == extensions.end())
2487 return true;
2488 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2489 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2490 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002491 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2492 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2493 return true;
2494 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2495 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2496 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002497 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2498 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2499 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002500
2501 return false;
2502};
2503
John Kessenich6090df02016-06-30 21:18:02 -06002504// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2505// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2506// Mutually recursive with convertGlslangToSpvType().
2507spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2508 const glslang::TTypeList* glslangMembers,
2509 glslang::TLayoutPacking explicitLayout,
2510 const glslang::TQualifier& qualifier)
2511{
2512 // Create a vector of struct types for SPIR-V to consume
2513 std::vector<spv::Id> spvMembers;
2514 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
John Kessenich6090df02016-06-30 21:18:02 -06002515 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2516 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2517 if (glslangMember.hiddenMember()) {
2518 ++memberDelta;
2519 if (type.getBasicType() == glslang::EbtBlock)
2520 memberRemapper[glslangMembers][i] = -1;
2521 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002522 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002523 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002524 if (filterMember(glslangMember))
2525 continue;
2526 }
John Kessenich6090df02016-06-30 21:18:02 -06002527 // modify just this child's view of the qualifier
2528 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2529 InheritQualifiers(memberQualifier, qualifier);
2530
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002531 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002532 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002533 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002534
2535 // recurse
2536 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2537 }
2538 }
2539
2540 // Make the SPIR-V type
2541 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002542 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002543 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2544
2545 // Decorate it
2546 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2547
2548 return spvType;
2549}
2550
2551void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2552 const glslang::TTypeList* glslangMembers,
2553 glslang::TLayoutPacking explicitLayout,
2554 const glslang::TQualifier& qualifier,
2555 spv::Id spvType)
2556{
2557 // Name and decorate the non-hidden members
2558 int offset = -1;
2559 int locationOffset = 0; // for use within the members of this struct
2560 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2561 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2562 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002563 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002564 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002565 if (filterMember(glslangMember))
2566 continue;
2567 }
John Kessenich6090df02016-06-30 21:18:02 -06002568
2569 // modify just this child's view of the qualifier
2570 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2571 InheritQualifiers(memberQualifier, qualifier);
2572
2573 // using -1 above to indicate a hidden member
2574 if (member >= 0) {
2575 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2576 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2577 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2578 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002579 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2580 type.getQualifier().storage == glslang::EvqVaryingOut) {
2581 if (type.getBasicType() == glslang::EbtBlock ||
2582 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002583 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2584 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2585 }
2586 }
2587 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2588
Rex Xu286ca432017-07-27 14:33:16 +08002589 if (type.getBasicType() == glslang::EbtBlock &&
2590 qualifier.storage == glslang::EvqBuffer) {
2591 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002592 std::vector<spv::Decoration> memory;
2593 TranslateMemoryDecoration(memberQualifier, memory);
2594 for (unsigned int i = 0; i < memory.size(); ++i)
2595 addMemberDecoration(spvType, member, memory[i]);
2596 }
2597
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002598 // Location assignment was already completed correctly by the front end,
2599 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002600 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002601 // ill-specified and decisions have been made to not allow this.
2602 if (! type.isArray() && memberQualifier.hasLocation())
2603 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002604
John Kessenich2f47bc92016-06-30 21:47:35 -06002605 if (qualifier.hasLocation()) // track for upcoming inheritance
2606 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2607
John Kessenich6090df02016-06-30 21:18:02 -06002608 // component, XFB, others
2609 if (glslangMember.getQualifier().hasComponent())
2610 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2611 if (glslangMember.getQualifier().hasXfbOffset())
2612 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2613 else if (explicitLayout != glslang::ElpNone) {
2614 // figure out what to do with offset, which is accumulating
2615 int nextOffset;
2616 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2617 if (offset >= 0)
2618 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2619 offset = nextOffset;
2620 }
2621
2622 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2623 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2624
2625 // built-in variable decorations
2626 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002627 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002628 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002629
2630#ifdef NV_EXTENSIONS
2631 if (builtIn == spv::BuiltInLayer) {
2632 // SPV_NV_viewport_array2 extension
2633 if (glslangMember.getQualifier().layoutViewportRelative){
2634 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2635 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2636 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2637 }
2638 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2639 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2640 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2641 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2642 }
2643 }
chaocdf3956c2017-02-14 14:52:34 -08002644 if (glslangMember.getQualifier().layoutPassthrough) {
2645 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2646 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2647 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2648 }
chaoc771d89f2017-01-13 01:10:53 -08002649#endif
John Kessenich6090df02016-06-30 21:18:02 -06002650 }
2651 }
2652
2653 // Decorate the structure
2654 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002655 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002656 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2657 builder.addCapability(spv::CapabilityGeometryStreams);
2658 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2659 }
2660 if (glslangIntermediate->getXfbMode()) {
2661 builder.addCapability(spv::CapabilityTransformFeedback);
2662 if (type.getQualifier().hasXfbStride())
2663 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2664 if (type.getQualifier().hasXfbBuffer())
2665 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2666 }
2667}
2668
John Kessenich6c292d32016-02-15 20:58:50 -07002669// Turn the expression forming the array size into an id.
2670// This is not quite trivial, because of specialization constants.
2671// Sometimes, a raw constant is turned into an Id, and sometimes
2672// a specialization constant expression is.
2673spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2674{
2675 // First, see if this is sized with a node, meaning a specialization constant:
2676 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2677 if (specNode != nullptr) {
2678 builder.clearAccessChain();
2679 specNode->traverse(this);
2680 return accessChainLoad(specNode->getAsTyped()->getType());
2681 }
qining25262b32016-05-06 17:25:16 -04002682
John Kessenich6c292d32016-02-15 20:58:50 -07002683 // Otherwise, need a compile-time (front end) size, get it:
2684 int size = arraySizes.getDimSize(dim);
2685 assert(size > 0);
2686 return builder.makeUintConstant(size);
2687}
2688
John Kessenich103bef92016-02-08 21:38:15 -07002689// Wrap the builder's accessChainLoad to:
2690// - localize handling of RelaxedPrecision
2691// - use the SPIR-V inferred type instead of another conversion of the glslang type
2692// (avoids unnecessary work and possible type punning for structures)
2693// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002694spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2695{
John Kessenich103bef92016-02-08 21:38:15 -07002696 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2697 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2698
2699 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002700 if (type.getBasicType() == glslang::EbtBool) {
2701 if (builder.isScalarType(nominalTypeId)) {
2702 // Conversion for bool
2703 spv::Id boolType = builder.makeBoolType();
2704 if (nominalTypeId != boolType)
2705 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2706 } else if (builder.isVectorType(nominalTypeId)) {
2707 // Conversion for bvec
2708 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2709 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2710 if (nominalTypeId != bvecType)
2711 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2712 }
2713 }
John Kessenich103bef92016-02-08 21:38:15 -07002714
2715 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002716}
2717
Rex Xu27253232016-02-23 17:51:09 +08002718// Wrap the builder's accessChainStore to:
2719// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002720//
2721// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002722void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2723{
2724 // Need to convert to abstract types when necessary
2725 if (type.getBasicType() == glslang::EbtBool) {
2726 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2727
2728 if (builder.isScalarType(nominalTypeId)) {
2729 // Conversion for bool
2730 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002731 if (nominalTypeId != boolType) {
2732 // keep these outside arguments, for determinant order-of-evaluation
2733 spv::Id one = builder.makeUintConstant(1);
2734 spv::Id zero = builder.makeUintConstant(0);
2735 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2736 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002737 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002738 } else if (builder.isVectorType(nominalTypeId)) {
2739 // Conversion for bvec
2740 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2741 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002742 if (nominalTypeId != bvecType) {
2743 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002744 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2745 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2746 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002747 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002748 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2749 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002750 }
2751 }
2752
2753 builder.accessChainStore(rvalue);
2754}
2755
John Kessenich4bf71552016-09-02 11:20:21 -06002756// For storing when types match at the glslang level, but not might match at the
2757// SPIR-V level.
2758//
2759// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002760// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002761// as in a member-decorated way.
2762//
2763// NOTE: This function can handle any store request; if it's not special it
2764// simplifies to a simple OpStore.
2765//
2766// Implicitly uses the existing builder.accessChain as the storage target.
2767void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2768{
John Kessenichb3e24e42016-09-11 12:33:43 -06002769 // we only do the complex path here if it's an aggregate
2770 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002771 accessChainStore(type, rValue);
2772 return;
2773 }
2774
John Kessenichb3e24e42016-09-11 12:33:43 -06002775 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002776 spv::Id rType = builder.getTypeId(rValue);
2777 spv::Id lValue = builder.accessChainGetLValue();
2778 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2779 if (lType == rType) {
2780 accessChainStore(type, rValue);
2781 return;
2782 }
2783
John Kessenichb3e24e42016-09-11 12:33:43 -06002784 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002785 // where the two types were the same type in GLSL. This requires member
2786 // by member copy, recursively.
2787
John Kessenichb3e24e42016-09-11 12:33:43 -06002788 // If an array, copy element by element.
2789 if (type.isArray()) {
2790 glslang::TType glslangElementType(type, 0);
2791 spv::Id elementRType = builder.getContainedTypeId(rType);
2792 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2793 // get the source member
2794 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002795
John Kessenichb3e24e42016-09-11 12:33:43 -06002796 // set up the target storage
2797 builder.clearAccessChain();
2798 builder.setAccessChainLValue(lValue);
2799 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002800
John Kessenichb3e24e42016-09-11 12:33:43 -06002801 // store the member
2802 multiTypeStore(glslangElementType, elementRValue);
2803 }
2804 } else {
2805 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002806
John Kessenichb3e24e42016-09-11 12:33:43 -06002807 // loop over structure members
2808 const glslang::TTypeList& members = *type.getStruct();
2809 for (int m = 0; m < (int)members.size(); ++m) {
2810 const glslang::TType& glslangMemberType = *members[m].type;
2811
2812 // get the source member
2813 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2814 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2815
2816 // set up the target storage
2817 builder.clearAccessChain();
2818 builder.setAccessChainLValue(lValue);
2819 builder.accessChainPush(builder.makeIntConstant(m));
2820
2821 // store the member
2822 multiTypeStore(glslangMemberType, memberRValue);
2823 }
John Kessenich4bf71552016-09-02 11:20:21 -06002824 }
2825}
2826
John Kessenichf85e8062015-12-19 13:57:10 -07002827// Decide whether or not this type should be
2828// decorated with offsets and strides, and if so
2829// whether std140 or std430 rules should be applied.
2830glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002831{
John Kessenichf85e8062015-12-19 13:57:10 -07002832 // has to be a block
2833 if (type.getBasicType() != glslang::EbtBlock)
2834 return glslang::ElpNone;
2835
2836 // has to be a uniform or buffer block
2837 if (type.getQualifier().storage != glslang::EvqUniform &&
2838 type.getQualifier().storage != glslang::EvqBuffer)
2839 return glslang::ElpNone;
2840
2841 // return the layout to use
2842 switch (type.getQualifier().layoutPacking) {
2843 case glslang::ElpStd140:
2844 case glslang::ElpStd430:
2845 return type.getQualifier().layoutPacking;
2846 default:
2847 return glslang::ElpNone;
2848 }
John Kessenich31ed4832015-09-09 17:51:38 -06002849}
2850
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002851// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002852int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002853{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002854 int size;
John Kessenich49987892015-12-29 17:11:44 -07002855 int stride;
2856 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002857
2858 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002859}
2860
John Kessenich49987892015-12-29 17:11:44 -07002861// 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 -07002862// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002863int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002864{
John Kessenich49987892015-12-29 17:11:44 -07002865 glslang::TType elementType;
2866 elementType.shallowCopy(matrixType);
2867 elementType.clearArraySizes();
2868
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002869 int size;
John Kessenich49987892015-12-29 17:11:44 -07002870 int stride;
2871 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2872
2873 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002874}
2875
John Kessenich5e4b1242015-08-06 22:53:06 -06002876// Given a member type of a struct, realign the current offset for it, and compute
2877// the next (not yet aligned) offset for the next member, which will get aligned
2878// on the next call.
2879// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2880// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2881// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002882void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002883 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002884{
2885 // this will get a positive value when deemed necessary
2886 nextOffset = -1;
2887
John Kessenich5e4b1242015-08-06 22:53:06 -06002888 // override anything in currentOffset with user-set offset
2889 if (memberType.getQualifier().hasOffset())
2890 currentOffset = memberType.getQualifier().layoutOffset;
2891
2892 // It could be that current linker usage in glslang updated all the layoutOffset,
2893 // in which case the following code does not matter. But, that's not quite right
2894 // once cross-compilation unit GLSL validation is done, as the original user
2895 // settings are needed in layoutOffset, and then the following will come into play.
2896
John Kessenichf85e8062015-12-19 13:57:10 -07002897 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002898 if (! memberType.getQualifier().hasOffset())
2899 currentOffset = -1;
2900
2901 return;
2902 }
2903
John Kessenichf85e8062015-12-19 13:57:10 -07002904 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002905 if (currentOffset < 0)
2906 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002907
John Kessenich5e4b1242015-08-06 22:53:06 -06002908 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2909 // but possibly not yet correctly aligned.
2910
2911 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002912 int dummyStride;
2913 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002914
2915 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002916 // TODO: make this consistent in early phases of code:
2917 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2918 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2919 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002920 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002921 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002922 int dummySize;
2923 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2924 if (componentAlignment <= 4)
2925 memberAlignment = componentAlignment;
2926 }
2927
2928 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002929 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002930
2931 // Bump up to vec4 if there is a bad straddle
2932 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2933 glslang::RoundToPow2(currentOffset, 16);
2934
John Kessenich5e4b1242015-08-06 22:53:06 -06002935 nextOffset = currentOffset + memberSize;
2936}
2937
David Netoa901ffe2016-06-08 14:11:40 +01002938void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002939{
David Netoa901ffe2016-06-08 14:11:40 +01002940 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2941 switch (glslangBuiltIn)
2942 {
2943 case glslang::EbvClipDistance:
2944 case glslang::EbvCullDistance:
2945 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002946#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08002947 case glslang::EbvViewportMaskNV:
2948 case glslang::EbvSecondaryPositionNV:
2949 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002950 case glslang::EbvPositionPerViewNV:
2951 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002952#endif
David Netoa901ffe2016-06-08 14:11:40 +01002953 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2954 // Alternately, we could just call this for any glslang built-in, since the
2955 // capability already guards against duplicates.
2956 TranslateBuiltInDecoration(glslangBuiltIn, false);
2957 break;
2958 default:
2959 // Capabilities were already generated when the struct was declared.
2960 break;
2961 }
John Kessenichebb50532016-05-16 19:22:05 -06002962}
2963
John Kessenich6fccb3c2016-09-19 16:01:41 -06002964bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002965{
John Kessenicheee9d532016-09-19 18:09:30 -06002966 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002967}
2968
John Kessenichd41993d2017-09-10 15:21:05 -06002969// Does parameter need a place to keep writes, separate from the original?
2970bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
2971{
2972 return qualifier != glslang::EvqConstReadOnly;
2973}
2974
2975// Is parameter pass-by-original?
2976bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
2977 bool implicitThisParam)
2978{
2979 if (implicitThisParam) // implicit this
2980 return true;
2981 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
2982 return false;
2983 return paramType.containsOpaque() || // sampler, etc.
2984 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
2985}
2986
John Kessenich140f3df2015-06-26 16:58:36 -06002987// Make all the functions, skeletally, without actually visiting their bodies.
2988void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2989{
John Kessenichfad62972017-07-18 02:35:46 -06002990 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
2991 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
2992 if (paramPrecision != spv::NoPrecision)
2993 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06002994 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06002995 };
2996
John Kessenich140f3df2015-06-26 16:58:36 -06002997 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2998 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002999 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003000 continue;
3001
3002 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003003 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003004 //
qining25262b32016-05-06 17:25:16 -04003005 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003006 // function. What it is an address of varies:
3007 //
John Kessenich4bf71552016-09-02 11:20:21 -06003008 // - "in" parameters not marked as "const" can be written to without modifying the calling
3009 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003010 //
3011 // - "const in" parameters can just be the r-value, as no writes need occur.
3012 //
John Kessenich4bf71552016-09-02 11:20:21 -06003013 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3014 // 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 -06003015
3016 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003017 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003018 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3019
John Kessenichfad62972017-07-18 02:35:46 -06003020 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3021 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003022
John Kessenichfad62972017-07-18 02:35:46 -06003023 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003024 for (int p = 0; p < (int)parameters.size(); ++p) {
3025 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3026 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003027 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003028 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003029 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003030 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3031 else
John Kessenich4bf71552016-09-02 11:20:21 -06003032 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003033 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003034 paramTypes.push_back(typeId);
3035 }
3036
3037 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003038 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3039 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003040 glslFunction->getName().c_str(), paramTypes,
3041 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003042 if (implicitThis)
3043 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003044
3045 // Track function to emit/call later
3046 functionMap[glslFunction->getName().c_str()] = function;
3047
3048 // Set the parameter id's
3049 for (int p = 0; p < (int)parameters.size(); ++p) {
3050 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3051 // give a name too
3052 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3053 }
3054 }
3055}
3056
3057// Process all the initializers, while skipping the functions and link objects
3058void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3059{
3060 builder.setBuildPoint(shaderEntry->getLastBlock());
3061 for (int i = 0; i < (int)initializers.size(); ++i) {
3062 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3063 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3064
3065 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003066 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003067 initializer->traverse(this);
3068 }
3069 }
3070}
3071
3072// Process all the functions, while skipping initializers.
3073void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3074{
3075 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3076 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003077 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003078 node->traverse(this);
3079 }
3080}
3081
3082void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3083{
qining25262b32016-05-06 17:25:16 -04003084 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003085 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003086 currentFunction = functionMap[node->getName().c_str()];
3087 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003088 builder.setBuildPoint(functionBlock);
3089}
3090
Rex Xu04db3f52015-09-16 11:44:02 +08003091void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003092{
Rex Xufc618912015-09-09 16:42:49 +08003093 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003094
3095 glslang::TSampler sampler = {};
3096 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003097 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003098 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3099 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3100 }
3101
John Kessenich140f3df2015-06-26 16:58:36 -06003102 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3103 builder.clearAccessChain();
3104 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003105
3106 // Special case l-value operands
3107 bool lvalue = false;
3108 switch (node.getOp()) {
3109 case glslang::EOpImageAtomicAdd:
3110 case glslang::EOpImageAtomicMin:
3111 case glslang::EOpImageAtomicMax:
3112 case glslang::EOpImageAtomicAnd:
3113 case glslang::EOpImageAtomicOr:
3114 case glslang::EOpImageAtomicXor:
3115 case glslang::EOpImageAtomicExchange:
3116 case glslang::EOpImageAtomicCompSwap:
3117 if (i == 0)
3118 lvalue = true;
3119 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003120 case glslang::EOpSparseImageLoad:
3121 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3122 lvalue = true;
3123 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003124 case glslang::EOpSparseTexture:
3125 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3126 lvalue = true;
3127 break;
3128 case glslang::EOpSparseTextureClamp:
3129 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3130 lvalue = true;
3131 break;
3132 case glslang::EOpSparseTextureLod:
3133 case glslang::EOpSparseTextureOffset:
3134 if (i == 3)
3135 lvalue = true;
3136 break;
3137 case glslang::EOpSparseTextureFetch:
3138 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3139 lvalue = true;
3140 break;
3141 case glslang::EOpSparseTextureFetchOffset:
3142 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3143 lvalue = true;
3144 break;
3145 case glslang::EOpSparseTextureLodOffset:
3146 case glslang::EOpSparseTextureGrad:
3147 case glslang::EOpSparseTextureOffsetClamp:
3148 if (i == 4)
3149 lvalue = true;
3150 break;
3151 case glslang::EOpSparseTextureGradOffset:
3152 case glslang::EOpSparseTextureGradClamp:
3153 if (i == 5)
3154 lvalue = true;
3155 break;
3156 case glslang::EOpSparseTextureGradOffsetClamp:
3157 if (i == 6)
3158 lvalue = true;
3159 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003160 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003161 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3162 lvalue = true;
3163 break;
3164 case glslang::EOpSparseTextureGatherOffset:
3165 case glslang::EOpSparseTextureGatherOffsets:
3166 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3167 lvalue = true;
3168 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003169#ifdef AMD_EXTENSIONS
3170 case glslang::EOpSparseTextureGatherLod:
3171 if (i == 3)
3172 lvalue = true;
3173 break;
3174 case glslang::EOpSparseTextureGatherLodOffset:
3175 case glslang::EOpSparseTextureGatherLodOffsets:
3176 if (i == 4)
3177 lvalue = true;
3178 break;
Rex Xu129799a2017-07-05 17:23:28 +08003179 case glslang::EOpSparseImageLoadLod:
3180 if (i == 3)
3181 lvalue = true;
3182 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003183#endif
Rex Xufc618912015-09-09 16:42:49 +08003184 default:
3185 break;
3186 }
3187
Rex Xu6b86d492015-09-16 17:48:22 +08003188 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003189 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003190 else
John Kessenich32cfd492016-02-02 12:37:46 -07003191 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003192 }
3193}
3194
John Kessenichfc51d282015-08-19 13:34:18 -06003195void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003196{
John Kessenichfc51d282015-08-19 13:34:18 -06003197 builder.clearAccessChain();
3198 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003199 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003200}
John Kessenich140f3df2015-06-26 16:58:36 -06003201
John Kessenichfc51d282015-08-19 13:34:18 -06003202spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3203{
John Kesseniche485c7a2017-05-31 18:50:53 -06003204 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003205 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003206
3207 builder.setLine(node->getLoc().line);
3208
John Kessenich8c8505c2016-07-26 12:50:38 -06003209 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003210
John Kessenichfc51d282015-08-19 13:34:18 -06003211 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003212 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3213 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3214 std::vector<spv::Id> arguments;
3215 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003216 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003217 else
3218 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003219 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003220
3221 spv::Builder::TextureParameters params = { };
3222 params.sampler = arguments[0];
3223
Rex Xu04db3f52015-09-16 11:44:02 +08003224 glslang::TCrackedTextureOp cracked;
3225 node->crackTexture(sampler, cracked);
3226
amhagan05506bb2017-06-13 16:53:02 -04003227 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003228
John Kessenichfc51d282015-08-19 13:34:18 -06003229 // Check for queries
3230 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003231 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3232 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003233 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003234
John Kessenichfc51d282015-08-19 13:34:18 -06003235 switch (node->getOp()) {
3236 case glslang::EOpImageQuerySize:
3237 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003238 if (arguments.size() > 1) {
3239 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003240 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003241 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003242 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003243 case glslang::EOpImageQuerySamples:
3244 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003245 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003246 case glslang::EOpTextureQueryLod:
3247 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003248 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003249 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003250 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003251 case glslang::EOpSparseTexelsResident:
3252 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003253 default:
3254 assert(0);
3255 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003256 }
John Kessenich140f3df2015-06-26 16:58:36 -06003257 }
3258
Rex Xufc618912015-09-09 16:42:49 +08003259 // Check for image functions other than queries
3260 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003261 std::vector<spv::Id> operands;
3262 auto opIt = arguments.begin();
3263 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003264
3265 // Handle subpass operations
3266 // TODO: GLSL should change to have the "MS" only on the type rather than the
3267 // built-in function.
3268 if (cracked.subpass) {
3269 // add on the (0,0) coordinate
3270 spv::Id zero = builder.makeIntConstant(0);
3271 std::vector<spv::Id> comps;
3272 comps.push_back(zero);
3273 comps.push_back(zero);
3274 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3275 if (sampler.ms) {
3276 operands.push_back(spv::ImageOperandsSampleMask);
3277 operands.push_back(*(opIt++));
3278 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003279 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3280 builder.setPrecision(result, precision);
3281 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003282 }
3283
John Kessenich56bab042015-09-16 10:54:31 -06003284 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003285#ifdef AMD_EXTENSIONS
3286 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3287#else
John Kessenich56bab042015-09-16 10:54:31 -06003288 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003289#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003290 if (sampler.ms) {
3291 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003292 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003293#ifdef AMD_EXTENSIONS
3294 } else if (cracked.lod) {
3295 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3296 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3297
3298 operands.push_back(spv::ImageOperandsLodMask);
3299 operands.push_back(*opIt);
3300#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003301 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003302 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3303 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003304
3305 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3306 builder.setPrecision(result, precision);
3307 return result;
Rex Xu129799a2017-07-05 17:23:28 +08003308#ifdef AMD_EXTENSIONS
3309 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3310#else
John Kessenich56bab042015-09-16 10:54:31 -06003311 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003312#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003313 if (sampler.ms) {
3314 operands.push_back(*(opIt + 1));
3315 operands.push_back(spv::ImageOperandsSampleMask);
3316 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003317#ifdef AMD_EXTENSIONS
3318 } else if (cracked.lod) {
3319 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3320 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3321
3322 operands.push_back(*(opIt + 1));
3323 operands.push_back(spv::ImageOperandsLodMask);
3324 operands.push_back(*opIt);
3325#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003326 } else
3327 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003328 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003329 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3330 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003331 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003332#ifdef AMD_EXTENSIONS
3333 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3334#else
Rex Xu5eafa472016-02-19 22:24:03 +08003335 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003336#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003337 builder.addCapability(spv::CapabilitySparseResidency);
3338 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3339 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3340
3341 if (sampler.ms) {
3342 operands.push_back(spv::ImageOperandsSampleMask);
3343 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003344#ifdef AMD_EXTENSIONS
3345 } else if (cracked.lod) {
3346 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3347 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3348
3349 operands.push_back(spv::ImageOperandsLodMask);
3350 operands.push_back(*opIt++);
3351#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003352 }
3353
3354 // Create the return type that was a special structure
3355 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003356 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003357 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3358 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3359
3360 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3361
3362 // Decode the return type
3363 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3364 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003365 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003366 // Process image atomic operations
3367
3368 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3369 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003370 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003371
John Kessenich8c8505c2016-07-26 12:50:38 -06003372 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003373 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003374
3375 std::vector<spv::Id> operands;
3376 operands.push_back(pointer);
3377 for (; opIt != arguments.end(); ++opIt)
3378 operands.push_back(*opIt);
3379
John Kessenich8c8505c2016-07-26 12:50:38 -06003380 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003381 }
3382 }
3383
amhagan05506bb2017-06-13 16:53:02 -04003384#ifdef AMD_EXTENSIONS
3385 // Check for fragment mask functions other than queries
3386 if (cracked.fragMask) {
3387 assert(sampler.ms);
3388
3389 auto opIt = arguments.begin();
3390 std::vector<spv::Id> operands;
3391
3392 // Extract the image if necessary
3393 if (builder.isSampledImage(params.sampler))
3394 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3395
3396 operands.push_back(params.sampler);
3397 ++opIt;
3398
3399 if (sampler.isSubpass()) {
3400 // add on the (0,0) coordinate
3401 spv::Id zero = builder.makeIntConstant(0);
3402 std::vector<spv::Id> comps;
3403 comps.push_back(zero);
3404 comps.push_back(zero);
3405 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3406 }
3407
3408 for (; opIt != arguments.end(); ++opIt)
3409 operands.push_back(*opIt);
3410
3411 spv::Op fragMaskOp = spv::OpNop;
3412 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3413 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3414 else if (node->getOp() == glslang::EOpFragmentFetch)
3415 fragMaskOp = spv::OpFragmentFetchAMD;
3416
3417 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3418 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3419 return builder.createOp(fragMaskOp, resultType(), operands);
3420 }
3421#endif
3422
Rex Xufc618912015-09-09 16:42:49 +08003423 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003424 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003425 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3426
John Kessenichfc51d282015-08-19 13:34:18 -06003427 // check for bias argument
3428 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003429#ifdef AMD_EXTENSIONS
3430 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3431#else
Rex Xu71519fe2015-11-11 15:35:47 +08003432 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003433#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003434 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003435#ifdef AMD_EXTENSIONS
3436 if (cracked.gather)
3437 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3438#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003439 if (cracked.offset)
3440 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003441#ifdef AMD_EXTENSIONS
3442 else if (cracked.offsets)
3443 ++nonBiasArgCount;
3444#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003445 if (cracked.grad)
3446 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003447 if (cracked.lodClamp)
3448 ++nonBiasArgCount;
3449 if (sparse)
3450 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003451
3452 if ((int)arguments.size() > nonBiasArgCount)
3453 bias = true;
3454 }
3455
John Kessenicha5c33d62016-06-02 23:45:21 -06003456 // See if the sampler param should really be just the SPV image part
3457 if (cracked.fetch) {
3458 // a fetch needs to have the image extracted first
3459 if (builder.isSampledImage(params.sampler))
3460 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3461 }
3462
Rex Xu225e0fc2016-11-17 17:47:59 +08003463#ifdef AMD_EXTENSIONS
3464 if (cracked.gather) {
3465 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3466 if (bias || cracked.lod ||
3467 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3468 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003469 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003470 }
3471 }
3472#endif
3473
John Kessenichfc51d282015-08-19 13:34:18 -06003474 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003475
John Kessenichfc51d282015-08-19 13:34:18 -06003476 params.coords = arguments[1];
3477 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003478 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003479
3480 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003481 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003482 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003483 ++extraArgs;
3484 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003485 params.Dref = arguments[2];
3486 ++extraArgs;
3487 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003488 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003489 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003490 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003491 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003492 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003493 dRefComp = builder.getNumComponents(params.coords) - 1;
3494 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003495 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3496 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003497
3498 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003499 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003500 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003501 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003502 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3503 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3504 noImplicitLod = true;
3505 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003506
3507 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003508 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003509 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003510 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003511 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003512
3513 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003514 if (cracked.grad) {
3515 params.gradX = arguments[2 + extraArgs];
3516 params.gradY = arguments[3 + extraArgs];
3517 extraArgs += 2;
3518 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003519
3520 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003521 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003522 params.offset = arguments[2 + extraArgs];
3523 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003524 } else if (cracked.offsets) {
3525 params.offsets = arguments[2 + extraArgs];
3526 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003527 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003528
3529 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003530 if (cracked.lodClamp) {
3531 params.lodClamp = arguments[2 + extraArgs];
3532 ++extraArgs;
3533 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003534
3535 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003536 if (sparse) {
3537 params.texelOut = arguments[2 + extraArgs];
3538 ++extraArgs;
3539 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003540
John Kessenich76d4dfc2016-06-16 12:43:23 -06003541 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003542 if (cracked.gather && ! sampler.shadow) {
3543 // default component is 0, if missing, otherwise an argument
3544 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003545 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003546 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003547 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003548 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003549 }
3550
3551 // bias
3552 if (bias) {
3553 params.bias = arguments[2 + extraArgs];
3554 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003555 }
John Kessenichfc51d282015-08-19 13:34:18 -06003556
John Kessenich65336482016-06-16 14:06:26 -06003557 // projective component (might not to move)
3558 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3559 // are divided by the last component of P."
3560 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3561 // unused components will appear after all used components."
3562 if (cracked.proj) {
3563 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3564 int projTargetComp;
3565 switch (sampler.dim) {
3566 case glslang::Esd1D: projTargetComp = 1; break;
3567 case glslang::Esd2D: projTargetComp = 2; break;
3568 case glslang::EsdRect: projTargetComp = 2; break;
3569 default: projTargetComp = projSourceComp; break;
3570 }
3571 // copy the projective coordinate if we have to
3572 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003573 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003574 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3575 projSourceComp);
3576 params.coords = builder.createCompositeInsert(projComp, params.coords,
3577 builder.getTypeId(params.coords), projTargetComp);
3578 }
3579 }
3580
John Kessenich8c8505c2016-07-26 12:50:38 -06003581 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003582}
3583
3584spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3585{
3586 // Grab the function's pointer from the previously created function
3587 spv::Function* function = functionMap[node->getName().c_str()];
3588 if (! function)
3589 return 0;
3590
3591 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3592 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3593
3594 // See comments in makeFunctions() for details about the semantics for parameter passing.
3595 //
3596 // These imply we need a four step process:
3597 // 1. Evaluate the arguments
3598 // 2. Allocate and make copies of in, out, and inout arguments
3599 // 3. Make the call
3600 // 4. Copy back the results
3601
3602 // 1. Evaluate the arguments
3603 std::vector<spv::Builder::AccessChain> lValues;
3604 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003605 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003606 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003607 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003608 // build l-value
3609 builder.clearAccessChain();
3610 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003611 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003612 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
3613 if (writableParam(qualifiers[a]) ||
3614 originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003615 // save l-value
3616 lValues.push_back(builder.getAccessChain());
3617 } else {
3618 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003619 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003620 }
3621 }
3622
3623 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3624 // copy the original into that space.
3625 //
3626 // Also, build up the list of actual arguments to pass in for the call
3627 int lValueCount = 0;
3628 int rValueCount = 0;
3629 std::vector<spv::Id> spvArgs;
3630 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003631 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003632 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003633 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003634 builder.setAccessChain(lValues[lValueCount]);
3635 arg = builder.accessChainGetLValue();
3636 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003637 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003638 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003639 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3640 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3641 // need to copy the input into output space
3642 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003643 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003644 builder.clearAccessChain();
3645 builder.setAccessChainLValue(arg);
3646 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003647 }
3648 ++lValueCount;
3649 } else {
3650 arg = rValues[rValueCount];
3651 ++rValueCount;
3652 }
3653 spvArgs.push_back(arg);
3654 }
3655
3656 // 3. Make the call.
3657 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003658 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003659
3660 // 4. Copy back out an "out" arguments.
3661 lValueCount = 0;
3662 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003663 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06003664 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
3665 ++lValueCount;
3666 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003667 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3668 spv::Id copy = builder.createLoad(spvArgs[a]);
3669 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003670 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003671 }
3672 ++lValueCount;
3673 }
3674 }
3675
3676 return result;
3677}
3678
3679// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003680spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3681 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003682 spv::Id typeId, spv::Id left, spv::Id right,
3683 glslang::TBasicType typeProxy, bool reduceComparison)
3684{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003685#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003686 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003687 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3688#else
Rex Xucabbb782017-03-24 13:41:14 +08003689 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003690 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003691#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003692 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003693
3694 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003695 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003696 bool comparison = false;
3697
3698 switch (op) {
3699 case glslang::EOpAdd:
3700 case glslang::EOpAddAssign:
3701 if (isFloat)
3702 binOp = spv::OpFAdd;
3703 else
3704 binOp = spv::OpIAdd;
3705 break;
3706 case glslang::EOpSub:
3707 case glslang::EOpSubAssign:
3708 if (isFloat)
3709 binOp = spv::OpFSub;
3710 else
3711 binOp = spv::OpISub;
3712 break;
3713 case glslang::EOpMul:
3714 case glslang::EOpMulAssign:
3715 if (isFloat)
3716 binOp = spv::OpFMul;
3717 else
3718 binOp = spv::OpIMul;
3719 break;
3720 case glslang::EOpVectorTimesScalar:
3721 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003722 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003723 if (builder.isVector(right))
3724 std::swap(left, right);
3725 assert(builder.isScalar(right));
3726 needMatchingVectors = false;
3727 binOp = spv::OpVectorTimesScalar;
3728 } else
3729 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003730 break;
3731 case glslang::EOpVectorTimesMatrix:
3732 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003733 binOp = spv::OpVectorTimesMatrix;
3734 break;
3735 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003736 binOp = spv::OpMatrixTimesVector;
3737 break;
3738 case glslang::EOpMatrixTimesScalar:
3739 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003740 binOp = spv::OpMatrixTimesScalar;
3741 break;
3742 case glslang::EOpMatrixTimesMatrix:
3743 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003744 binOp = spv::OpMatrixTimesMatrix;
3745 break;
3746 case glslang::EOpOuterProduct:
3747 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003748 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003749 break;
3750
3751 case glslang::EOpDiv:
3752 case glslang::EOpDivAssign:
3753 if (isFloat)
3754 binOp = spv::OpFDiv;
3755 else if (isUnsigned)
3756 binOp = spv::OpUDiv;
3757 else
3758 binOp = spv::OpSDiv;
3759 break;
3760 case glslang::EOpMod:
3761 case glslang::EOpModAssign:
3762 if (isFloat)
3763 binOp = spv::OpFMod;
3764 else if (isUnsigned)
3765 binOp = spv::OpUMod;
3766 else
3767 binOp = spv::OpSMod;
3768 break;
3769 case glslang::EOpRightShift:
3770 case glslang::EOpRightShiftAssign:
3771 if (isUnsigned)
3772 binOp = spv::OpShiftRightLogical;
3773 else
3774 binOp = spv::OpShiftRightArithmetic;
3775 break;
3776 case glslang::EOpLeftShift:
3777 case glslang::EOpLeftShiftAssign:
3778 binOp = spv::OpShiftLeftLogical;
3779 break;
3780 case glslang::EOpAnd:
3781 case glslang::EOpAndAssign:
3782 binOp = spv::OpBitwiseAnd;
3783 break;
3784 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003785 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003786 binOp = spv::OpLogicalAnd;
3787 break;
3788 case glslang::EOpInclusiveOr:
3789 case glslang::EOpInclusiveOrAssign:
3790 binOp = spv::OpBitwiseOr;
3791 break;
3792 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003793 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003794 binOp = spv::OpLogicalOr;
3795 break;
3796 case glslang::EOpExclusiveOr:
3797 case glslang::EOpExclusiveOrAssign:
3798 binOp = spv::OpBitwiseXor;
3799 break;
3800 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003801 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003802 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003803 break;
3804
3805 case glslang::EOpLessThan:
3806 case glslang::EOpGreaterThan:
3807 case glslang::EOpLessThanEqual:
3808 case glslang::EOpGreaterThanEqual:
3809 case glslang::EOpEqual:
3810 case glslang::EOpNotEqual:
3811 case glslang::EOpVectorEqual:
3812 case glslang::EOpVectorNotEqual:
3813 comparison = true;
3814 break;
3815 default:
3816 break;
3817 }
3818
John Kessenich7c1aa102015-10-15 13:29:11 -06003819 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003820 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003821 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003822 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003823 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003824
3825 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003826 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003827 builder.promoteScalar(precision, left, right);
3828
qining25262b32016-05-06 17:25:16 -04003829 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3830 addDecoration(result, noContraction);
3831 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003832 }
3833
3834 if (! comparison)
3835 return 0;
3836
John Kessenich7c1aa102015-10-15 13:29:11 -06003837 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003838
John Kessenich4583b612016-08-07 19:14:22 -06003839 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3840 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003841 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003842
3843 switch (op) {
3844 case glslang::EOpLessThan:
3845 if (isFloat)
3846 binOp = spv::OpFOrdLessThan;
3847 else if (isUnsigned)
3848 binOp = spv::OpULessThan;
3849 else
3850 binOp = spv::OpSLessThan;
3851 break;
3852 case glslang::EOpGreaterThan:
3853 if (isFloat)
3854 binOp = spv::OpFOrdGreaterThan;
3855 else if (isUnsigned)
3856 binOp = spv::OpUGreaterThan;
3857 else
3858 binOp = spv::OpSGreaterThan;
3859 break;
3860 case glslang::EOpLessThanEqual:
3861 if (isFloat)
3862 binOp = spv::OpFOrdLessThanEqual;
3863 else if (isUnsigned)
3864 binOp = spv::OpULessThanEqual;
3865 else
3866 binOp = spv::OpSLessThanEqual;
3867 break;
3868 case glslang::EOpGreaterThanEqual:
3869 if (isFloat)
3870 binOp = spv::OpFOrdGreaterThanEqual;
3871 else if (isUnsigned)
3872 binOp = spv::OpUGreaterThanEqual;
3873 else
3874 binOp = spv::OpSGreaterThanEqual;
3875 break;
3876 case glslang::EOpEqual:
3877 case glslang::EOpVectorEqual:
3878 if (isFloat)
3879 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003880 else if (isBool)
3881 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003882 else
3883 binOp = spv::OpIEqual;
3884 break;
3885 case glslang::EOpNotEqual:
3886 case glslang::EOpVectorNotEqual:
3887 if (isFloat)
3888 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003889 else if (isBool)
3890 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003891 else
3892 binOp = spv::OpINotEqual;
3893 break;
3894 default:
3895 break;
3896 }
3897
qining25262b32016-05-06 17:25:16 -04003898 if (binOp != spv::OpNop) {
3899 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3900 addDecoration(result, noContraction);
3901 return builder.setPrecision(result, precision);
3902 }
John Kessenich140f3df2015-06-26 16:58:36 -06003903
3904 return 0;
3905}
3906
John Kessenich04bb8a02015-12-12 12:28:14 -07003907//
3908// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3909// These can be any of:
3910//
3911// matrix * scalar
3912// scalar * matrix
3913// matrix * matrix linear algebraic
3914// matrix * vector
3915// vector * matrix
3916// matrix * matrix componentwise
3917// matrix op matrix op in {+, -, /}
3918// matrix op scalar op in {+, -, /}
3919// scalar op matrix op in {+, -, /}
3920//
qining25262b32016-05-06 17:25:16 -04003921spv::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 -07003922{
3923 bool firstClass = true;
3924
3925 // First, handle first-class matrix operations (* and matrix/scalar)
3926 switch (op) {
3927 case spv::OpFDiv:
3928 if (builder.isMatrix(left) && builder.isScalar(right)) {
3929 // turn matrix / scalar into a multiply...
3930 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3931 op = spv::OpMatrixTimesScalar;
3932 } else
3933 firstClass = false;
3934 break;
3935 case spv::OpMatrixTimesScalar:
3936 if (builder.isMatrix(right))
3937 std::swap(left, right);
3938 assert(builder.isScalar(right));
3939 break;
3940 case spv::OpVectorTimesMatrix:
3941 assert(builder.isVector(left));
3942 assert(builder.isMatrix(right));
3943 break;
3944 case spv::OpMatrixTimesVector:
3945 assert(builder.isMatrix(left));
3946 assert(builder.isVector(right));
3947 break;
3948 case spv::OpMatrixTimesMatrix:
3949 assert(builder.isMatrix(left));
3950 assert(builder.isMatrix(right));
3951 break;
3952 default:
3953 firstClass = false;
3954 break;
3955 }
3956
qining25262b32016-05-06 17:25:16 -04003957 if (firstClass) {
3958 spv::Id result = builder.createBinOp(op, typeId, left, right);
3959 addDecoration(result, noContraction);
3960 return builder.setPrecision(result, precision);
3961 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003962
LoopDawg592860c2016-06-09 08:57:35 -06003963 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003964 // The result type of all of them is the same type as the (a) matrix operand.
3965 // The algorithm is to:
3966 // - break the matrix(es) into vectors
3967 // - smear any scalar to a vector
3968 // - do vector operations
3969 // - make a matrix out the vector results
3970 switch (op) {
3971 case spv::OpFAdd:
3972 case spv::OpFSub:
3973 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003974 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003975 case spv::OpFMul:
3976 {
3977 // one time set up...
3978 bool leftMat = builder.isMatrix(left);
3979 bool rightMat = builder.isMatrix(right);
3980 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3981 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3982 spv::Id scalarType = builder.getScalarTypeId(typeId);
3983 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3984 std::vector<spv::Id> results;
3985 spv::Id smearVec = spv::NoResult;
3986 if (builder.isScalar(left))
3987 smearVec = builder.smearScalar(precision, left, vecType);
3988 else if (builder.isScalar(right))
3989 smearVec = builder.smearScalar(precision, right, vecType);
3990
3991 // do each vector op
3992 for (unsigned int c = 0; c < numCols; ++c) {
3993 std::vector<unsigned int> indexes;
3994 indexes.push_back(c);
3995 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3996 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003997 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3998 addDecoration(result, noContraction);
3999 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004000 }
4001
4002 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004003 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07004004 }
4005 default:
4006 assert(0);
4007 return spv::NoResult;
4008 }
4009}
4010
qining25262b32016-05-06 17:25:16 -04004011spv::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 -06004012{
4013 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004014 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004015 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004016#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004017 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004018 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4019#else
Rex Xucabbb782017-03-24 13:41:14 +08004020 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08004021 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004022#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004023
4024 switch (op) {
4025 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004026 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004027 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004028 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04004029 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004030 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004031 unaryOp = spv::OpSNegate;
4032 break;
4033
4034 case glslang::EOpLogicalNot:
4035 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004036 unaryOp = spv::OpLogicalNot;
4037 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004038 case glslang::EOpBitwiseNot:
4039 unaryOp = spv::OpNot;
4040 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004041
John Kessenich140f3df2015-06-26 16:58:36 -06004042 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004043 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004044 break;
4045 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004046 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004047 break;
4048 case glslang::EOpTranspose:
4049 unaryOp = spv::OpTranspose;
4050 break;
4051
4052 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004053 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004054 break;
4055 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004056 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004057 break;
4058 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004059 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004060 break;
4061 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004062 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004063 break;
4064 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004065 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004066 break;
4067 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004068 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004069 break;
4070 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004071 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004072 break;
4073 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004074 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004075 break;
4076
4077 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004078 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004079 break;
4080 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004081 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004082 break;
4083 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004084 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004085 break;
4086 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004087 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004088 break;
4089 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004090 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004091 break;
4092 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004093 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004094 break;
4095
4096 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004097 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004098 break;
4099 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004100 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004101 break;
4102
4103 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004104 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004105 break;
4106 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004107 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004108 break;
4109 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004110 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004111 break;
4112 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004113 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004114 break;
4115 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004116 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004117 break;
4118 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004119 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004120 break;
4121
4122 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004123 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004124 break;
4125 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004126 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004127 break;
4128 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004129 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004130 break;
4131 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004132 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004133 break;
4134 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004135 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004136 break;
4137 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004138 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004139 break;
4140
4141 case glslang::EOpIsNan:
4142 unaryOp = spv::OpIsNan;
4143 break;
4144 case glslang::EOpIsInf:
4145 unaryOp = spv::OpIsInf;
4146 break;
LoopDawg592860c2016-06-09 08:57:35 -06004147 case glslang::EOpIsFinite:
4148 unaryOp = spv::OpIsFinite;
4149 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004150
Rex Xucbc426e2015-12-15 16:03:10 +08004151 case glslang::EOpFloatBitsToInt:
4152 case glslang::EOpFloatBitsToUint:
4153 case glslang::EOpIntBitsToFloat:
4154 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004155 case glslang::EOpDoubleBitsToInt64:
4156 case glslang::EOpDoubleBitsToUint64:
4157 case glslang::EOpInt64BitsToDouble:
4158 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004159#ifdef AMD_EXTENSIONS
4160 case glslang::EOpFloat16BitsToInt16:
4161 case glslang::EOpFloat16BitsToUint16:
4162 case glslang::EOpInt16BitsToFloat16:
4163 case glslang::EOpUint16BitsToFloat16:
4164#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004165 unaryOp = spv::OpBitcast;
4166 break;
4167
John Kessenich140f3df2015-06-26 16:58:36 -06004168 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004169 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004170 break;
4171 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004172 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004173 break;
4174 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004175 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004176 break;
4177 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004178 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004179 break;
4180 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004181 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004182 break;
4183 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004184 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004185 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004186 case glslang::EOpPackSnorm4x8:
4187 libCall = spv::GLSLstd450PackSnorm4x8;
4188 break;
4189 case glslang::EOpUnpackSnorm4x8:
4190 libCall = spv::GLSLstd450UnpackSnorm4x8;
4191 break;
4192 case glslang::EOpPackUnorm4x8:
4193 libCall = spv::GLSLstd450PackUnorm4x8;
4194 break;
4195 case glslang::EOpUnpackUnorm4x8:
4196 libCall = spv::GLSLstd450UnpackUnorm4x8;
4197 break;
4198 case glslang::EOpPackDouble2x32:
4199 libCall = spv::GLSLstd450PackDouble2x32;
4200 break;
4201 case glslang::EOpUnpackDouble2x32:
4202 libCall = spv::GLSLstd450UnpackDouble2x32;
4203 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004204
Rex Xu8ff43de2016-04-22 16:51:45 +08004205 case glslang::EOpPackInt2x32:
4206 case glslang::EOpUnpackInt2x32:
4207 case glslang::EOpPackUint2x32:
4208 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004209 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004210 break;
4211
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004212#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004213 case glslang::EOpPackInt2x16:
4214 case glslang::EOpUnpackInt2x16:
4215 case glslang::EOpPackUint2x16:
4216 case glslang::EOpUnpackUint2x16:
4217 case glslang::EOpPackInt4x16:
4218 case glslang::EOpUnpackInt4x16:
4219 case glslang::EOpPackUint4x16:
4220 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004221 case glslang::EOpPackFloat2x16:
4222 case glslang::EOpUnpackFloat2x16:
4223 unaryOp = spv::OpBitcast;
4224 break;
4225#endif
4226
John Kessenich140f3df2015-06-26 16:58:36 -06004227 case glslang::EOpDPdx:
4228 unaryOp = spv::OpDPdx;
4229 break;
4230 case glslang::EOpDPdy:
4231 unaryOp = spv::OpDPdy;
4232 break;
4233 case glslang::EOpFwidth:
4234 unaryOp = spv::OpFwidth;
4235 break;
4236 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004237 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004238 unaryOp = spv::OpDPdxFine;
4239 break;
4240 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004241 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004242 unaryOp = spv::OpDPdyFine;
4243 break;
4244 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004245 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004246 unaryOp = spv::OpFwidthFine;
4247 break;
4248 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004249 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004250 unaryOp = spv::OpDPdxCoarse;
4251 break;
4252 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004253 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004254 unaryOp = spv::OpDPdyCoarse;
4255 break;
4256 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004257 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004258 unaryOp = spv::OpFwidthCoarse;
4259 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004260 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004261 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004262 libCall = spv::GLSLstd450InterpolateAtCentroid;
4263 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004264 case glslang::EOpAny:
4265 unaryOp = spv::OpAny;
4266 break;
4267 case glslang::EOpAll:
4268 unaryOp = spv::OpAll;
4269 break;
4270
4271 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004272 if (isFloat)
4273 libCall = spv::GLSLstd450FAbs;
4274 else
4275 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004276 break;
4277 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004278 if (isFloat)
4279 libCall = spv::GLSLstd450FSign;
4280 else
4281 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004282 break;
4283
John Kessenichfc51d282015-08-19 13:34:18 -06004284 case glslang::EOpAtomicCounterIncrement:
4285 case glslang::EOpAtomicCounterDecrement:
4286 case glslang::EOpAtomicCounter:
4287 {
4288 // Handle all of the atomics in one place, in createAtomicOperation()
4289 std::vector<spv::Id> operands;
4290 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004291 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004292 }
4293
John Kessenichfc51d282015-08-19 13:34:18 -06004294 case glslang::EOpBitFieldReverse:
4295 unaryOp = spv::OpBitReverse;
4296 break;
4297 case glslang::EOpBitCount:
4298 unaryOp = spv::OpBitCount;
4299 break;
4300 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004301 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004302 break;
4303 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004304 if (isUnsigned)
4305 libCall = spv::GLSLstd450FindUMsb;
4306 else
4307 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004308 break;
4309
Rex Xu574ab042016-04-14 16:53:07 +08004310 case glslang::EOpBallot:
4311 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004312 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004313 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004314 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004315#ifdef AMD_EXTENSIONS
4316 case glslang::EOpMinInvocations:
4317 case glslang::EOpMaxInvocations:
4318 case glslang::EOpAddInvocations:
4319 case glslang::EOpMinInvocationsNonUniform:
4320 case glslang::EOpMaxInvocationsNonUniform:
4321 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004322 case glslang::EOpMinInvocationsInclusiveScan:
4323 case glslang::EOpMaxInvocationsInclusiveScan:
4324 case glslang::EOpAddInvocationsInclusiveScan:
4325 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4326 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4327 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4328 case glslang::EOpMinInvocationsExclusiveScan:
4329 case glslang::EOpMaxInvocationsExclusiveScan:
4330 case glslang::EOpAddInvocationsExclusiveScan:
4331 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4332 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4333 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004334#endif
Rex Xu51596642016-09-21 18:56:12 +08004335 {
4336 std::vector<spv::Id> operands;
4337 operands.push_back(operand);
4338 return createInvocationsOperation(op, typeId, operands, typeProxy);
4339 }
Rex Xu9d93a232016-05-05 12:30:44 +08004340
4341#ifdef AMD_EXTENSIONS
4342 case glslang::EOpMbcnt:
4343 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4344 libCall = spv::MbcntAMD;
4345 break;
4346
4347 case glslang::EOpCubeFaceIndex:
4348 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4349 libCall = spv::CubeFaceIndexAMD;
4350 break;
4351
4352 case glslang::EOpCubeFaceCoord:
4353 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4354 libCall = spv::CubeFaceCoordAMD;
4355 break;
4356#endif
Rex Xu338b1852016-05-05 20:38:33 +08004357
John Kessenich140f3df2015-06-26 16:58:36 -06004358 default:
4359 return 0;
4360 }
4361
4362 spv::Id id;
4363 if (libCall >= 0) {
4364 std::vector<spv::Id> args;
4365 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004366 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004367 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004368 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004369 }
John Kessenich140f3df2015-06-26 16:58:36 -06004370
qining25262b32016-05-06 17:25:16 -04004371 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004372 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004373}
4374
John Kessenich7a53f762016-01-20 11:19:27 -07004375// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004376spv::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 -07004377{
4378 // Handle unary operations vector by vector.
4379 // The result type is the same type as the original type.
4380 // The algorithm is to:
4381 // - break the matrix into vectors
4382 // - apply the operation to each vector
4383 // - make a matrix out the vector results
4384
4385 // get the types sorted out
4386 int numCols = builder.getNumColumns(operand);
4387 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004388 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4389 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004390 std::vector<spv::Id> results;
4391
4392 // do each vector op
4393 for (int c = 0; c < numCols; ++c) {
4394 std::vector<unsigned int> indexes;
4395 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004396 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4397 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4398 addDecoration(destVec, noContraction);
4399 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004400 }
4401
4402 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004403 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004404}
4405
Rex Xu73e3ce72016-04-27 18:48:17 +08004406spv::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 -06004407{
4408 spv::Op convOp = spv::OpNop;
4409 spv::Id zero = 0;
4410 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004411 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004412
4413 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4414
4415 switch (op) {
4416 case glslang::EOpConvIntToBool:
4417 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004418 case glslang::EOpConvInt64ToBool:
4419 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004420#ifdef AMD_EXTENSIONS
4421 case glslang::EOpConvInt16ToBool:
4422 case glslang::EOpConvUint16ToBool:
4423#endif
4424 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4425 zero = builder.makeUint64Constant(0);
4426#ifdef AMD_EXTENSIONS
4427 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4428 zero = builder.makeUint16Constant(0);
4429#endif
4430 else
4431 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004432 zero = makeSmearedConstant(zero, vectorSize);
4433 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4434
4435 case glslang::EOpConvFloatToBool:
4436 zero = builder.makeFloatConstant(0.0F);
4437 zero = makeSmearedConstant(zero, vectorSize);
4438 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4439
4440 case glslang::EOpConvDoubleToBool:
4441 zero = builder.makeDoubleConstant(0.0);
4442 zero = makeSmearedConstant(zero, vectorSize);
4443 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4444
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004445#ifdef AMD_EXTENSIONS
4446 case glslang::EOpConvFloat16ToBool:
4447 zero = builder.makeFloat16Constant(0.0F);
4448 zero = makeSmearedConstant(zero, vectorSize);
4449 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4450#endif
4451
John Kessenich140f3df2015-06-26 16:58:36 -06004452 case glslang::EOpConvBoolToFloat:
4453 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004454 zero = builder.makeFloatConstant(0.0F);
4455 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004456 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004457
John Kessenich140f3df2015-06-26 16:58:36 -06004458 case glslang::EOpConvBoolToDouble:
4459 convOp = spv::OpSelect;
4460 zero = builder.makeDoubleConstant(0.0);
4461 one = builder.makeDoubleConstant(1.0);
4462 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004463
4464#ifdef AMD_EXTENSIONS
4465 case glslang::EOpConvBoolToFloat16:
4466 convOp = spv::OpSelect;
4467 zero = builder.makeFloat16Constant(0.0F);
4468 one = builder.makeFloat16Constant(1.0F);
4469 break;
4470#endif
4471
John Kessenich140f3df2015-06-26 16:58:36 -06004472 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004473 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004474#ifdef AMD_EXTENSIONS
4475 case glslang::EOpConvBoolToInt16:
4476#endif
4477 if (op == glslang::EOpConvBoolToInt64)
4478 zero = builder.makeInt64Constant(0);
4479#ifdef AMD_EXTENSIONS
4480 else if (op == glslang::EOpConvBoolToInt16)
4481 zero = builder.makeInt16Constant(0);
4482#endif
4483 else
4484 zero = builder.makeIntConstant(0);
4485
4486 if (op == glslang::EOpConvBoolToInt64)
4487 one = builder.makeInt64Constant(1);
4488#ifdef AMD_EXTENSIONS
4489 else if (op == glslang::EOpConvBoolToInt16)
4490 one = builder.makeInt16Constant(1);
4491#endif
4492 else
4493 one = builder.makeIntConstant(1);
4494
John Kessenich140f3df2015-06-26 16:58:36 -06004495 convOp = spv::OpSelect;
4496 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004497
John Kessenich140f3df2015-06-26 16:58:36 -06004498 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004499 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004500#ifdef AMD_EXTENSIONS
4501 case glslang::EOpConvBoolToUint16:
4502#endif
4503 if (op == glslang::EOpConvBoolToUint64)
4504 zero = builder.makeUint64Constant(0);
4505#ifdef AMD_EXTENSIONS
4506 else if (op == glslang::EOpConvBoolToUint16)
4507 zero = builder.makeUint16Constant(0);
4508#endif
4509 else
4510 zero = builder.makeUintConstant(0);
4511
4512 if (op == glslang::EOpConvBoolToUint64)
4513 one = builder.makeUint64Constant(1);
4514#ifdef AMD_EXTENSIONS
4515 else if (op == glslang::EOpConvBoolToUint16)
4516 one = builder.makeUint16Constant(1);
4517#endif
4518 else
4519 one = builder.makeUintConstant(1);
4520
John Kessenich140f3df2015-06-26 16:58:36 -06004521 convOp = spv::OpSelect;
4522 break;
4523
4524 case glslang::EOpConvIntToFloat:
4525 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004526 case glslang::EOpConvInt64ToFloat:
4527 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004528#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004529 case glslang::EOpConvInt16ToFloat:
4530 case glslang::EOpConvInt16ToDouble:
4531 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004532 case glslang::EOpConvIntToFloat16:
4533 case glslang::EOpConvInt64ToFloat16:
4534#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004535 convOp = spv::OpConvertSToF;
4536 break;
4537
4538 case glslang::EOpConvUintToFloat:
4539 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004540 case glslang::EOpConvUint64ToFloat:
4541 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004542#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004543 case glslang::EOpConvUint16ToFloat:
4544 case glslang::EOpConvUint16ToDouble:
4545 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004546 case glslang::EOpConvUintToFloat16:
4547 case glslang::EOpConvUint64ToFloat16:
4548#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004549 convOp = spv::OpConvertUToF;
4550 break;
4551
4552 case glslang::EOpConvDoubleToFloat:
4553 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004554#ifdef AMD_EXTENSIONS
4555 case glslang::EOpConvDoubleToFloat16:
4556 case glslang::EOpConvFloat16ToDouble:
4557 case glslang::EOpConvFloatToFloat16:
4558 case glslang::EOpConvFloat16ToFloat:
4559#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004560 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004561 if (builder.isMatrixType(destType))
4562 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004563 break;
4564
4565 case glslang::EOpConvFloatToInt:
4566 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004567 case glslang::EOpConvFloatToInt64:
4568 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004569#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004570 case glslang::EOpConvFloatToInt16:
4571 case glslang::EOpConvDoubleToInt16:
4572 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004573 case glslang::EOpConvFloat16ToInt:
4574 case glslang::EOpConvFloat16ToInt64:
4575#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004576 convOp = spv::OpConvertFToS;
4577 break;
4578
4579 case glslang::EOpConvUintToInt:
4580 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004581 case glslang::EOpConvUint64ToInt64:
4582 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004583#ifdef AMD_EXTENSIONS
4584 case glslang::EOpConvUint16ToInt16:
4585 case glslang::EOpConvInt16ToUint16:
4586#endif
qininge24aa5e2016-04-07 15:40:27 -04004587 if (builder.isInSpecConstCodeGenMode()) {
4588 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004589 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4590 zero = builder.makeUint64Constant(0);
4591#ifdef AMD_EXTENSIONS
4592 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4593 zero = builder.makeUint16Constant(0);
4594#endif
4595 else
4596 zero = builder.makeUintConstant(0);
4597
qining189b2032016-04-12 23:16:20 -04004598 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004599 // Use OpIAdd, instead of OpBitcast to do the conversion when
4600 // generating for OpSpecConstantOp instruction.
4601 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4602 }
4603 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004604 convOp = spv::OpBitcast;
4605 break;
4606
4607 case glslang::EOpConvFloatToUint:
4608 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004609 case glslang::EOpConvFloatToUint64:
4610 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004611#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004612 case glslang::EOpConvFloatToUint16:
4613 case glslang::EOpConvDoubleToUint16:
4614 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004615 case glslang::EOpConvFloat16ToUint:
4616 case glslang::EOpConvFloat16ToUint64:
4617#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004618 convOp = spv::OpConvertFToU;
4619 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004620
4621 case glslang::EOpConvIntToInt64:
4622 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004623#ifdef AMD_EXTENSIONS
4624 case glslang::EOpConvIntToInt16:
4625 case glslang::EOpConvInt16ToInt:
4626 case glslang::EOpConvInt64ToInt16:
4627 case glslang::EOpConvInt16ToInt64:
4628#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004629 convOp = spv::OpSConvert;
4630 break;
4631
4632 case glslang::EOpConvUintToUint64:
4633 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004634#ifdef AMD_EXTENSIONS
4635 case glslang::EOpConvUintToUint16:
4636 case glslang::EOpConvUint16ToUint:
4637 case glslang::EOpConvUint64ToUint16:
4638 case glslang::EOpConvUint16ToUint64:
4639#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004640 convOp = spv::OpUConvert;
4641 break;
4642
4643 case glslang::EOpConvIntToUint64:
4644 case glslang::EOpConvInt64ToUint:
4645 case glslang::EOpConvUint64ToInt:
4646 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004647#ifdef AMD_EXTENSIONS
4648 case glslang::EOpConvInt16ToUint:
4649 case glslang::EOpConvUintToInt16:
4650 case glslang::EOpConvInt16ToUint64:
4651 case glslang::EOpConvUint64ToInt16:
4652 case glslang::EOpConvUint16ToInt:
4653 case glslang::EOpConvIntToUint16:
4654 case glslang::EOpConvUint16ToInt64:
4655 case glslang::EOpConvInt64ToUint16:
4656#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004657 // OpSConvert/OpUConvert + OpBitCast
4658 switch (op) {
4659 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004660#ifdef AMD_EXTENSIONS
4661 case glslang::EOpConvInt16ToUint64:
4662#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004663 convOp = spv::OpSConvert;
4664 type = builder.makeIntType(64);
4665 break;
4666 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004667#ifdef AMD_EXTENSIONS
4668 case glslang::EOpConvInt16ToUint:
4669#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004670 convOp = spv::OpSConvert;
4671 type = builder.makeIntType(32);
4672 break;
4673 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004674#ifdef AMD_EXTENSIONS
4675 case glslang::EOpConvUint16ToInt:
4676#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004677 convOp = spv::OpUConvert;
4678 type = builder.makeUintType(32);
4679 break;
4680 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004681#ifdef AMD_EXTENSIONS
4682 case glslang::EOpConvUint16ToInt64:
4683#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004684 convOp = spv::OpUConvert;
4685 type = builder.makeUintType(64);
4686 break;
Rex Xucabbb782017-03-24 13:41:14 +08004687#ifdef AMD_EXTENSIONS
4688 case glslang::EOpConvUintToInt16:
4689 case glslang::EOpConvUint64ToInt16:
4690 convOp = spv::OpUConvert;
4691 type = builder.makeUintType(16);
4692 break;
4693 case glslang::EOpConvIntToUint16:
4694 case glslang::EOpConvInt64ToUint16:
4695 convOp = spv::OpSConvert;
4696 type = builder.makeIntType(16);
4697 break;
4698#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004699 default:
4700 assert(0);
4701 break;
4702 }
4703
4704 if (vectorSize > 0)
4705 type = builder.makeVectorType(type, vectorSize);
4706
4707 operand = builder.createUnaryOp(convOp, type, operand);
4708
4709 if (builder.isInSpecConstCodeGenMode()) {
4710 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004711#ifdef AMD_EXTENSIONS
4712 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4713 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4714 zero = builder.makeUint64Constant(0);
4715 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4716 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4717 zero = builder.makeUint16Constant(0);
4718 else
4719 zero = builder.makeUintConstant(0);
4720#else
4721 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4722 zero = builder.makeUint64Constant(0);
4723 else
4724 zero = builder.makeUintConstant(0);
4725#endif
4726
Rex Xu8ff43de2016-04-22 16:51:45 +08004727 zero = makeSmearedConstant(zero, vectorSize);
4728 // Use OpIAdd, instead of OpBitcast to do the conversion when
4729 // generating for OpSpecConstantOp instruction.
4730 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4731 }
4732 // For normal run-time conversion instruction, use OpBitcast.
4733 convOp = spv::OpBitcast;
4734 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004735 default:
4736 break;
4737 }
4738
4739 spv::Id result = 0;
4740 if (convOp == spv::OpNop)
4741 return result;
4742
4743 if (convOp == spv::OpSelect) {
4744 zero = makeSmearedConstant(zero, vectorSize);
4745 one = makeSmearedConstant(one, vectorSize);
4746 result = builder.createTriOp(convOp, destType, operand, one, zero);
4747 } else
4748 result = builder.createUnaryOp(convOp, destType, operand);
4749
John Kessenich32cfd492016-02-02 12:37:46 -07004750 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004751}
4752
4753spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4754{
4755 if (vectorSize == 0)
4756 return constant;
4757
4758 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4759 std::vector<spv::Id> components;
4760 for (int c = 0; c < vectorSize; ++c)
4761 components.push_back(constant);
4762 return builder.makeCompositeConstant(vectorTypeId, components);
4763}
4764
John Kessenich426394d2015-07-23 10:22:48 -06004765// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004766spv::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 -06004767{
4768 spv::Op opCode = spv::OpNop;
4769
4770 switch (op) {
4771 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004772 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004773 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004774 opCode = spv::OpAtomicIAdd;
4775 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004776 case glslang::EOpAtomicCounterSubtract:
4777 opCode = spv::OpAtomicISub;
4778 break;
John Kessenich426394d2015-07-23 10:22:48 -06004779 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004780 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004781 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08004782 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004783 break;
4784 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004785 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004786 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08004787 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004788 break;
4789 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004790 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004791 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004792 opCode = spv::OpAtomicAnd;
4793 break;
4794 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004795 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004796 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004797 opCode = spv::OpAtomicOr;
4798 break;
4799 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004800 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004801 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004802 opCode = spv::OpAtomicXor;
4803 break;
4804 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004805 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004806 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004807 opCode = spv::OpAtomicExchange;
4808 break;
4809 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004810 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004811 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004812 opCode = spv::OpAtomicCompareExchange;
4813 break;
4814 case glslang::EOpAtomicCounterIncrement:
4815 opCode = spv::OpAtomicIIncrement;
4816 break;
4817 case glslang::EOpAtomicCounterDecrement:
4818 opCode = spv::OpAtomicIDecrement;
4819 break;
4820 case glslang::EOpAtomicCounter:
4821 opCode = spv::OpAtomicLoad;
4822 break;
4823 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004824 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004825 break;
4826 }
4827
Rex Xue8fe8b02017-09-26 15:42:56 +08004828 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
4829 builder.addCapability(spv::CapabilityInt64Atomics);
4830
John Kessenich426394d2015-07-23 10:22:48 -06004831 // Sort out the operands
4832 // - mapping from glslang -> SPV
4833 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004834 // - compare-exchange swaps the value and comparator
4835 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06004836 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06004837 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4838 auto opIt = operands.begin(); // walk the glslang operands
4839 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004840 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4841 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4842 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004843 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4844 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004845 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004846 spvAtomicOperands.push_back(*(opIt + 1));
4847 spvAtomicOperands.push_back(*opIt);
4848 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004849 }
John Kessenich426394d2015-07-23 10:22:48 -06004850
John Kessenich3e60a6f2015-09-14 22:45:16 -06004851 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004852 for (; opIt != operands.end(); ++opIt)
4853 spvAtomicOperands.push_back(*opIt);
4854
John Kessenich48d6e792017-10-06 21:21:48 -06004855 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
4856
4857 // GLSL and HLSL atomic-counter decrement return post-decrement value,
4858 // while SPIR-V returns pre-decrement value. Translate between these semantics.
4859 if (op == glslang::EOpAtomicCounterDecrement)
4860 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
4861
4862 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06004863}
4864
John Kessenich91cef522016-05-05 16:45:40 -06004865// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004866spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004867{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004868#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004869 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004870 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004871#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004872
Rex Xu51596642016-09-21 18:56:12 +08004873 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004874 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004875 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4876
chaocf200da82016-12-20 12:44:35 -08004877 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4878 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004879 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4880 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004881 } else if (op == glslang::EOpAnyInvocation ||
4882 op == glslang::EOpAllInvocations ||
4883 op == glslang::EOpAllInvocationsEqual) {
4884 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4885 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004886 } else {
4887 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004888#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004889 if (op == glslang::EOpMinInvocationsNonUniform ||
4890 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004891 op == glslang::EOpAddInvocationsNonUniform ||
4892 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4893 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4894 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4895 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4896 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4897 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004898 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004899#endif
Rex Xu51596642016-09-21 18:56:12 +08004900
4901 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004902#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004903 switch (op) {
4904 case glslang::EOpMinInvocations:
4905 case glslang::EOpMaxInvocations:
4906 case glslang::EOpAddInvocations:
4907 case glslang::EOpMinInvocationsNonUniform:
4908 case glslang::EOpMaxInvocationsNonUniform:
4909 case glslang::EOpAddInvocationsNonUniform:
4910 groupOperation = spv::GroupOperationReduce;
4911 spvGroupOperands.push_back(groupOperation);
4912 break;
4913 case glslang::EOpMinInvocationsInclusiveScan:
4914 case glslang::EOpMaxInvocationsInclusiveScan:
4915 case glslang::EOpAddInvocationsInclusiveScan:
4916 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4917 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4918 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4919 groupOperation = spv::GroupOperationInclusiveScan;
4920 spvGroupOperands.push_back(groupOperation);
4921 break;
4922 case glslang::EOpMinInvocationsExclusiveScan:
4923 case glslang::EOpMaxInvocationsExclusiveScan:
4924 case glslang::EOpAddInvocationsExclusiveScan:
4925 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4926 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4927 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4928 groupOperation = spv::GroupOperationExclusiveScan;
4929 spvGroupOperands.push_back(groupOperation);
4930 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004931 default:
4932 break;
Rex Xu430ef402016-10-14 17:22:23 +08004933 }
Rex Xu9d93a232016-05-05 12:30:44 +08004934#endif
Rex Xu51596642016-09-21 18:56:12 +08004935 }
4936
4937 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4938 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004939
4940 switch (op) {
4941 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004942 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004943 break;
John Kessenich91cef522016-05-05 16:45:40 -06004944 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004945 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004946 break;
John Kessenich91cef522016-05-05 16:45:40 -06004947 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004948 opCode = spv::OpSubgroupAllEqualKHR;
4949 break;
Rex Xu51596642016-09-21 18:56:12 +08004950 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004951 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004952 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004953 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004954 break;
4955 case glslang::EOpReadFirstInvocation:
4956 opCode = spv::OpSubgroupFirstInvocationKHR;
4957 break;
4958 case glslang::EOpBallot:
4959 {
4960 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4961 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4962 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4963 //
4964 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4965 //
4966 spv::Id uintType = builder.makeUintType(32);
4967 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4968 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4969
4970 std::vector<spv::Id> components;
4971 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4972 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4973
4974 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4975 return builder.createUnaryOp(spv::OpBitcast, typeId,
4976 builder.createCompositeConstruct(uvec2Type, components));
4977 }
4978
Rex Xu9d93a232016-05-05 12:30:44 +08004979#ifdef AMD_EXTENSIONS
4980 case glslang::EOpMinInvocations:
4981 case glslang::EOpMaxInvocations:
4982 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004983 case glslang::EOpMinInvocationsInclusiveScan:
4984 case glslang::EOpMaxInvocationsInclusiveScan:
4985 case glslang::EOpAddInvocationsInclusiveScan:
4986 case glslang::EOpMinInvocationsExclusiveScan:
4987 case glslang::EOpMaxInvocationsExclusiveScan:
4988 case glslang::EOpAddInvocationsExclusiveScan:
4989 if (op == glslang::EOpMinInvocations ||
4990 op == glslang::EOpMinInvocationsInclusiveScan ||
4991 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004992 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004993 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004994 else {
4995 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004996 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004997 else
Rex Xu51596642016-09-21 18:56:12 +08004998 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004999 }
Rex Xu430ef402016-10-14 17:22:23 +08005000 } else if (op == glslang::EOpMaxInvocations ||
5001 op == glslang::EOpMaxInvocationsInclusiveScan ||
5002 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005003 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005004 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005005 else {
5006 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005007 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005008 else
Rex Xu51596642016-09-21 18:56:12 +08005009 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005010 }
5011 } else {
5012 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005013 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005014 else
Rex Xu51596642016-09-21 18:56:12 +08005015 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005016 }
5017
Rex Xu2bbbe062016-08-23 15:41:05 +08005018 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005019 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005020
5021 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005022 case glslang::EOpMinInvocationsNonUniform:
5023 case glslang::EOpMaxInvocationsNonUniform:
5024 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005025 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5026 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5027 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5028 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5029 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5030 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5031 if (op == glslang::EOpMinInvocationsNonUniform ||
5032 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5033 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005034 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005035 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005036 else {
5037 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005038 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005039 else
Rex Xu51596642016-09-21 18:56:12 +08005040 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005041 }
5042 }
Rex Xu430ef402016-10-14 17:22:23 +08005043 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5044 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5045 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005046 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005047 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005048 else {
5049 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005050 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005051 else
Rex Xu51596642016-09-21 18:56:12 +08005052 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005053 }
5054 }
5055 else {
5056 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005057 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005058 else
Rex Xu51596642016-09-21 18:56:12 +08005059 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005060 }
5061
Rex Xu2bbbe062016-08-23 15:41:05 +08005062 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005063 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005064
5065 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005066#endif
John Kessenich91cef522016-05-05 16:45:40 -06005067 default:
5068 logger->missingFunctionality("invocation operation");
5069 return spv::NoResult;
5070 }
Rex Xu51596642016-09-21 18:56:12 +08005071
5072 assert(opCode != spv::OpNop);
5073 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005074}
5075
Rex Xu2bbbe062016-08-23 15:41:05 +08005076// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005077spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005078{
Rex Xub7072052016-09-26 15:53:40 +08005079#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005080 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5081 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005082 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005083 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005084 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5085 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5086 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005087#else
5088 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5089 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005090 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5091 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005092#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005093
5094 // Handle group invocation operations scalar by scalar.
5095 // The result type is the same type as the original type.
5096 // The algorithm is to:
5097 // - break the vector into scalars
5098 // - apply the operation to each scalar
5099 // - make a vector out the scalar results
5100
5101 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005102 int numComponents = builder.getNumComponents(operands[0]);
5103 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005104 std::vector<spv::Id> results;
5105
5106 // do each scalar op
5107 for (int comp = 0; comp < numComponents; ++comp) {
5108 std::vector<unsigned int> indexes;
5109 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005110 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005111 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005112 if (op == spv::OpSubgroupReadInvocationKHR) {
5113 spvGroupOperands.push_back(scalar);
5114 spvGroupOperands.push_back(operands[1]);
5115 } else if (op == spv::OpGroupBroadcast) {
5116 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005117 spvGroupOperands.push_back(scalar);
5118 spvGroupOperands.push_back(operands[1]);
5119 } else {
chaocf200da82016-12-20 12:44:35 -08005120 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005121 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005122 spvGroupOperands.push_back(scalar);
5123 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005124
Rex Xub7072052016-09-26 15:53:40 +08005125 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005126 }
5127
5128 // put the pieces together
5129 return builder.createCompositeConstruct(typeId, results);
5130}
Rex Xu2bbbe062016-08-23 15:41:05 +08005131
John Kessenich5e4b1242015-08-06 22:53:06 -06005132spv::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 -06005133{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005134#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005135 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005136 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5137#else
Rex Xucabbb782017-03-24 13:41:14 +08005138 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005139 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005140#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005141
John Kessenich140f3df2015-06-26 16:58:36 -06005142 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005143 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005144 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005145 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005146 spv::Id typeId0 = 0;
5147 if (consumedOperands > 0)
5148 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005149 spv::Id typeId1 = 0;
5150 if (consumedOperands > 1)
5151 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005152 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005153
5154 switch (op) {
5155 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005156 if (isFloat)
5157 libCall = spv::GLSLstd450FMin;
5158 else if (isUnsigned)
5159 libCall = spv::GLSLstd450UMin;
5160 else
5161 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005162 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005163 break;
5164 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005165 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005166 break;
5167 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005168 if (isFloat)
5169 libCall = spv::GLSLstd450FMax;
5170 else if (isUnsigned)
5171 libCall = spv::GLSLstd450UMax;
5172 else
5173 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005174 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005175 break;
5176 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005177 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005178 break;
5179 case glslang::EOpDot:
5180 opCode = spv::OpDot;
5181 break;
5182 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005183 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005184 break;
5185
5186 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005187 if (isFloat)
5188 libCall = spv::GLSLstd450FClamp;
5189 else if (isUnsigned)
5190 libCall = spv::GLSLstd450UClamp;
5191 else
5192 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005193 builder.promoteScalar(precision, operands.front(), operands[1]);
5194 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005195 break;
5196 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005197 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5198 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005199 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005200 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005201 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005202 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005203 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005204 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005205 break;
5206 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005207 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005208 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005209 break;
5210 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005211 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005212 builder.promoteScalar(precision, operands[0], operands[2]);
5213 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005214 break;
5215
5216 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005217 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005218 break;
5219 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005220 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005221 break;
5222 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005223 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005224 break;
5225 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005226 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005227 break;
5228 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005229 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005230 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005231 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005232 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005233 libCall = spv::GLSLstd450InterpolateAtSample;
5234 break;
5235 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005236 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005237 libCall = spv::GLSLstd450InterpolateAtOffset;
5238 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005239 case glslang::EOpAddCarry:
5240 opCode = spv::OpIAddCarry;
5241 typeId = builder.makeStructResultType(typeId0, typeId0);
5242 consumedOperands = 2;
5243 break;
5244 case glslang::EOpSubBorrow:
5245 opCode = spv::OpISubBorrow;
5246 typeId = builder.makeStructResultType(typeId0, typeId0);
5247 consumedOperands = 2;
5248 break;
5249 case glslang::EOpUMulExtended:
5250 opCode = spv::OpUMulExtended;
5251 typeId = builder.makeStructResultType(typeId0, typeId0);
5252 consumedOperands = 2;
5253 break;
5254 case glslang::EOpIMulExtended:
5255 opCode = spv::OpSMulExtended;
5256 typeId = builder.makeStructResultType(typeId0, typeId0);
5257 consumedOperands = 2;
5258 break;
5259 case glslang::EOpBitfieldExtract:
5260 if (isUnsigned)
5261 opCode = spv::OpBitFieldUExtract;
5262 else
5263 opCode = spv::OpBitFieldSExtract;
5264 break;
5265 case glslang::EOpBitfieldInsert:
5266 opCode = spv::OpBitFieldInsert;
5267 break;
5268
5269 case glslang::EOpFma:
5270 libCall = spv::GLSLstd450Fma;
5271 break;
5272 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005273 {
5274 libCall = spv::GLSLstd450FrexpStruct;
5275 assert(builder.isPointerType(typeId1));
5276 typeId1 = builder.getContainedTypeId(typeId1);
5277#ifdef AMD_EXTENSIONS
5278 int width = builder.getScalarTypeWidth(typeId1);
5279#else
5280 int width = 32;
5281#endif
5282 if (builder.getNumComponents(operands[0]) == 1)
5283 frexpIntType = builder.makeIntegerType(width, true);
5284 else
5285 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5286 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5287 consumedOperands = 1;
5288 }
John Kessenich55e7d112015-11-15 21:33:39 -07005289 break;
5290 case glslang::EOpLdexp:
5291 libCall = spv::GLSLstd450Ldexp;
5292 break;
5293
Rex Xu574ab042016-04-14 16:53:07 +08005294 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005295 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005296
Rex Xu9d93a232016-05-05 12:30:44 +08005297#ifdef AMD_EXTENSIONS
5298 case glslang::EOpSwizzleInvocations:
5299 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5300 libCall = spv::SwizzleInvocationsAMD;
5301 break;
5302 case glslang::EOpSwizzleInvocationsMasked:
5303 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5304 libCall = spv::SwizzleInvocationsMaskedAMD;
5305 break;
5306 case glslang::EOpWriteInvocation:
5307 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5308 libCall = spv::WriteInvocationAMD;
5309 break;
5310
5311 case glslang::EOpMin3:
5312 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5313 if (isFloat)
5314 libCall = spv::FMin3AMD;
5315 else {
5316 if (isUnsigned)
5317 libCall = spv::UMin3AMD;
5318 else
5319 libCall = spv::SMin3AMD;
5320 }
5321 break;
5322 case glslang::EOpMax3:
5323 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5324 if (isFloat)
5325 libCall = spv::FMax3AMD;
5326 else {
5327 if (isUnsigned)
5328 libCall = spv::UMax3AMD;
5329 else
5330 libCall = spv::SMax3AMD;
5331 }
5332 break;
5333 case glslang::EOpMid3:
5334 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5335 if (isFloat)
5336 libCall = spv::FMid3AMD;
5337 else {
5338 if (isUnsigned)
5339 libCall = spv::UMid3AMD;
5340 else
5341 libCall = spv::SMid3AMD;
5342 }
5343 break;
5344
5345 case glslang::EOpInterpolateAtVertex:
5346 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5347 libCall = spv::InterpolateAtVertexAMD;
5348 break;
5349#endif
5350
John Kessenich140f3df2015-06-26 16:58:36 -06005351 default:
5352 return 0;
5353 }
5354
5355 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005356 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005357 // Use an extended instruction from the standard library.
5358 // Construct the call arguments, without modifying the original operands vector.
5359 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5360 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005361 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005362 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005363 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005364 case 0:
5365 // should all be handled by visitAggregate and createNoArgOperation
5366 assert(0);
5367 return 0;
5368 case 1:
5369 // should all be handled by createUnaryOperation
5370 assert(0);
5371 return 0;
5372 case 2:
5373 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5374 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005375 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005376 // anything 3 or over doesn't have l-value operands, so all should be consumed
5377 assert(consumedOperands == operands.size());
5378 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005379 break;
5380 }
5381 }
5382
John Kessenich55e7d112015-11-15 21:33:39 -07005383 // Decode the return types that were structures
5384 switch (op) {
5385 case glslang::EOpAddCarry:
5386 case glslang::EOpSubBorrow:
5387 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5388 id = builder.createCompositeExtract(id, typeId0, 0);
5389 break;
5390 case glslang::EOpUMulExtended:
5391 case glslang::EOpIMulExtended:
5392 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5393 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5394 break;
5395 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005396 {
5397 assert(operands.size() == 2);
5398 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5399 // "exp" is floating-point type (from HLSL intrinsic)
5400 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5401 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5402 builder.createStore(member1, operands[1]);
5403 } else
5404 // "exp" is integer type (from GLSL built-in function)
5405 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5406 id = builder.createCompositeExtract(id, typeId0, 0);
5407 }
John Kessenich55e7d112015-11-15 21:33:39 -07005408 break;
5409 default:
5410 break;
5411 }
5412
John Kessenich32cfd492016-02-02 12:37:46 -07005413 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005414}
5415
Rex Xu9d93a232016-05-05 12:30:44 +08005416// Intrinsics with no arguments (or no return value, and no precision).
5417spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005418{
5419 // TODO: get the barrier operands correct
5420
5421 switch (op) {
5422 case glslang::EOpEmitVertex:
5423 builder.createNoResultOp(spv::OpEmitVertex);
5424 return 0;
5425 case glslang::EOpEndPrimitive:
5426 builder.createNoResultOp(spv::OpEndPrimitive);
5427 return 0;
5428 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005429 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005430 return 0;
5431 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005432 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005433 return 0;
5434 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005435 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005436 return 0;
5437 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005438 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005439 return 0;
5440 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005441 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005442 return 0;
5443 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005444 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005445 return 0;
5446 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005447 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005448 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005449 case glslang::EOpAllMemoryBarrierWithGroupSync:
5450 // Control barrier with non-"None" semantic is also a memory barrier.
5451 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5452 return 0;
5453 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5454 // Control barrier with non-"None" semantic is also a memory barrier.
5455 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5456 return 0;
5457 case glslang::EOpWorkgroupMemoryBarrier:
5458 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5459 return 0;
5460 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5461 // Control barrier with non-"None" semantic is also a memory barrier.
5462 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5463 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005464#ifdef AMD_EXTENSIONS
5465 case glslang::EOpTime:
5466 {
5467 std::vector<spv::Id> args; // Dummy arguments
5468 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5469 return builder.setPrecision(id, precision);
5470 }
5471#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005472 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005473 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005474 return 0;
5475 }
5476}
5477
5478spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5479{
John Kessenich2f273362015-07-18 22:34:27 -06005480 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005481 spv::Id id;
5482 if (symbolValues.end() != iter) {
5483 id = iter->second;
5484 return id;
5485 }
5486
5487 // it was not found, create it
5488 id = createSpvVariable(symbol);
5489 symbolValues[symbol->getId()] = id;
5490
Rex Xuc884b4a2016-06-29 15:03:44 +08005491 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005492 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005493 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005494 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005495 if (symbol->getType().getQualifier().hasSpecConstantId())
5496 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005497 if (symbol->getQualifier().hasIndex())
5498 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5499 if (symbol->getQualifier().hasComponent())
5500 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5501 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005502 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005503 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005504 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005505 if (symbol->getQualifier().hasXfbBuffer())
5506 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5507 if (symbol->getQualifier().hasXfbOffset())
5508 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5509 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005510 // atomic counters use this:
5511 if (symbol->getQualifier().hasOffset())
5512 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005513 }
5514
scygan2c864272016-05-18 18:09:17 +02005515 if (symbol->getQualifier().hasLocation())
5516 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005517 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005518 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005519 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005520 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005521 }
John Kessenich140f3df2015-06-26 16:58:36 -06005522 if (symbol->getQualifier().hasSet())
5523 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005524 else if (IsDescriptorResource(symbol->getType())) {
5525 // default to 0
5526 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5527 }
John Kessenich140f3df2015-06-26 16:58:36 -06005528 if (symbol->getQualifier().hasBinding())
5529 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005530 if (symbol->getQualifier().hasAttachment())
5531 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005532 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005533 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005534 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005535 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005536 if (symbol->getQualifier().hasXfbBuffer())
5537 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5538 }
5539
Rex Xu1da878f2016-02-21 20:59:01 +08005540 if (symbol->getType().isImage()) {
5541 std::vector<spv::Decoration> memory;
5542 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5543 for (unsigned int i = 0; i < memory.size(); ++i)
5544 addDecoration(id, memory[i]);
5545 }
5546
John Kessenich140f3df2015-06-26 16:58:36 -06005547 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005548 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005549 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005550 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005551
John Kessenichecba76f2017-01-06 00:34:48 -07005552#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005553 if (builtIn == spv::BuiltInSampleMask) {
5554 spv::Decoration decoration;
5555 // GL_NV_sample_mask_override_coverage extension
5556 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005557 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005558 else
5559 decoration = (spv::Decoration)spv::DecorationMax;
5560 addDecoration(id, decoration);
5561 if (decoration != spv::DecorationMax) {
5562 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5563 }
5564 }
chaoc771d89f2017-01-13 01:10:53 -08005565 else if (builtIn == spv::BuiltInLayer) {
5566 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005567 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005568 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5569 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5570 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5571 }
John Kessenichb41bff62017-08-11 13:07:17 -06005572 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005573 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5574 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5575 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5576 }
5577 }
5578
chaoc6e5acae2016-12-20 13:28:52 -08005579 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005580 addDecoration(id, spv::DecorationPassthroughNV);
5581 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005582 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5583 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005584#endif
5585
John Kessenich140f3df2015-06-26 16:58:36 -06005586 return id;
5587}
5588
John Kessenich55e7d112015-11-15 21:33:39 -07005589// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005590void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5591{
John Kessenich4016e382016-07-15 11:53:56 -06005592 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005593 builder.addDecoration(id, dec);
5594}
5595
John Kessenich55e7d112015-11-15 21:33:39 -07005596// If 'dec' is valid, add a one-operand decoration to an object
5597void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5598{
John Kessenich4016e382016-07-15 11:53:56 -06005599 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005600 builder.addDecoration(id, dec, value);
5601}
5602
5603// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005604void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5605{
John Kessenich4016e382016-07-15 11:53:56 -06005606 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005607 builder.addMemberDecoration(id, (unsigned)member, dec);
5608}
5609
John Kessenich92187592016-02-01 13:45:25 -07005610// If 'dec' is valid, add a one-operand decoration to a struct member
5611void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5612{
John Kessenich4016e382016-07-15 11:53:56 -06005613 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005614 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5615}
5616
John Kessenich55e7d112015-11-15 21:33:39 -07005617// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005618// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005619//
5620// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5621//
5622// Recursively walk the nodes. The nodes form a tree whose leaves are
5623// regular constants, which themselves are trees that createSpvConstant()
5624// recursively walks. So, this function walks the "top" of the tree:
5625// - emit specialization constant-building instructions for specConstant
5626// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005627spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005628{
John Kessenich7cc0e282016-03-20 00:46:02 -06005629 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005630
qining4f4bb812016-04-03 23:55:17 -04005631 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005632 if (! node.getQualifier().specConstant) {
5633 // hand off to the non-spec-constant path
5634 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5635 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005636 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005637 nextConst, false);
5638 }
5639
5640 // We now know we have a specialization constant to build
5641
John Kessenichd94c0032016-05-30 19:29:40 -06005642 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005643 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5644 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5645 std::vector<spv::Id> dimConstId;
5646 for (int dim = 0; dim < 3; ++dim) {
5647 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5648 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5649 if (specConst)
5650 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5651 }
5652 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5653 }
5654
5655 // An AST node labelled as specialization constant should be a symbol node.
5656 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5657 if (auto* sn = node.getAsSymbolNode()) {
5658 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005659 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5660 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5661 // will set the builder into spec constant op instruction generating mode.
5662 sub_tree->traverse(this);
5663 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005664 } else if (auto* const_union_array = &sn->getConstArray()){
5665 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005666 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5667 builder.addName(id, sn->getName().c_str());
5668 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005669 }
5670 }
qining4f4bb812016-04-03 23:55:17 -04005671
5672 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5673 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005674 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005675 exit(1);
5676 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005677}
5678
John Kessenich140f3df2015-06-26 16:58:36 -06005679// Use 'consts' as the flattened glslang source of scalar constants to recursively
5680// build the aggregate SPIR-V constant.
5681//
5682// If there are not enough elements present in 'consts', 0 will be substituted;
5683// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5684//
qining08408382016-03-21 09:51:37 -04005685spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005686{
5687 // vector of constants for SPIR-V
5688 std::vector<spv::Id> spvConsts;
5689
5690 // Type is used for struct and array constants
5691 spv::Id typeId = convertGlslangToSpvType(glslangType);
5692
5693 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005694 glslang::TType elementType(glslangType, 0);
5695 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005696 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005697 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005698 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005699 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005700 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005701 } else if (glslangType.getStruct()) {
5702 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5703 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005704 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005705 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005706 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5707 bool zero = nextConst >= consts.size();
5708 switch (glslangType.getBasicType()) {
5709 case glslang::EbtInt:
5710 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5711 break;
5712 case glslang::EbtUint:
5713 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5714 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005715 case glslang::EbtInt64:
5716 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5717 break;
5718 case glslang::EbtUint64:
5719 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5720 break;
Rex Xucabbb782017-03-24 13:41:14 +08005721#ifdef AMD_EXTENSIONS
5722 case glslang::EbtInt16:
5723 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5724 break;
5725 case glslang::EbtUint16:
5726 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5727 break;
5728#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005729 case glslang::EbtFloat:
5730 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5731 break;
5732 case glslang::EbtDouble:
5733 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5734 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005735#ifdef AMD_EXTENSIONS
5736 case glslang::EbtFloat16:
5737 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5738 break;
5739#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005740 case glslang::EbtBool:
5741 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5742 break;
5743 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005744 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005745 break;
5746 }
5747 ++nextConst;
5748 }
5749 } else {
5750 // we have a non-aggregate (scalar) constant
5751 bool zero = nextConst >= consts.size();
5752 spv::Id scalar = 0;
5753 switch (glslangType.getBasicType()) {
5754 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005755 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005756 break;
5757 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005758 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005759 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005760 case glslang::EbtInt64:
5761 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5762 break;
5763 case glslang::EbtUint64:
5764 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5765 break;
Rex Xucabbb782017-03-24 13:41:14 +08005766#ifdef AMD_EXTENSIONS
5767 case glslang::EbtInt16:
5768 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5769 break;
5770 case glslang::EbtUint16:
5771 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5772 break;
5773#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005774 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005775 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005776 break;
5777 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005778 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005779 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005780#ifdef AMD_EXTENSIONS
5781 case glslang::EbtFloat16:
5782 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5783 break;
5784#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005785 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005786 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005787 break;
5788 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005789 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005790 break;
5791 }
5792 ++nextConst;
5793 return scalar;
5794 }
5795
5796 return builder.makeCompositeConstant(typeId, spvConsts);
5797}
5798
John Kessenich7c1aa102015-10-15 13:29:11 -06005799// Return true if the node is a constant or symbol whose reading has no
5800// non-trivial observable cost or effect.
5801bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5802{
5803 // don't know what this is
5804 if (node == nullptr)
5805 return false;
5806
5807 // a constant is safe
5808 if (node->getAsConstantUnion() != nullptr)
5809 return true;
5810
5811 // not a symbol means non-trivial
5812 if (node->getAsSymbolNode() == nullptr)
5813 return false;
5814
5815 // a symbol, depends on what's being read
5816 switch (node->getType().getQualifier().storage) {
5817 case glslang::EvqTemporary:
5818 case glslang::EvqGlobal:
5819 case glslang::EvqIn:
5820 case glslang::EvqInOut:
5821 case glslang::EvqConst:
5822 case glslang::EvqConstReadOnly:
5823 case glslang::EvqUniform:
5824 return true;
5825 default:
5826 return false;
5827 }
qining25262b32016-05-06 17:25:16 -04005828}
John Kessenich7c1aa102015-10-15 13:29:11 -06005829
5830// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005831// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005832// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005833// Return true if trivial.
5834bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5835{
5836 if (node == nullptr)
5837 return false;
5838
John Kessenich84cc15f2017-05-24 16:44:47 -06005839 // count non scalars as trivial, as well as anything coming from HLSL
5840 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005841 return true;
5842
John Kessenich7c1aa102015-10-15 13:29:11 -06005843 // symbols and constants are trivial
5844 if (isTrivialLeaf(node))
5845 return true;
5846
5847 // otherwise, it needs to be a simple operation or one or two leaf nodes
5848
5849 // not a simple operation
5850 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5851 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5852 if (binaryNode == nullptr && unaryNode == nullptr)
5853 return false;
5854
5855 // not on leaf nodes
5856 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5857 return false;
5858
5859 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5860 return false;
5861 }
5862
5863 switch (node->getAsOperator()->getOp()) {
5864 case glslang::EOpLogicalNot:
5865 case glslang::EOpConvIntToBool:
5866 case glslang::EOpConvUintToBool:
5867 case glslang::EOpConvFloatToBool:
5868 case glslang::EOpConvDoubleToBool:
5869 case glslang::EOpEqual:
5870 case glslang::EOpNotEqual:
5871 case glslang::EOpLessThan:
5872 case glslang::EOpGreaterThan:
5873 case glslang::EOpLessThanEqual:
5874 case glslang::EOpGreaterThanEqual:
5875 case glslang::EOpIndexDirect:
5876 case glslang::EOpIndexDirectStruct:
5877 case glslang::EOpLogicalXor:
5878 case glslang::EOpAny:
5879 case glslang::EOpAll:
5880 return true;
5881 default:
5882 return false;
5883 }
5884}
5885
5886// Emit short-circuiting code, where 'right' is never evaluated unless
5887// the left side is true (for &&) or false (for ||).
5888spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5889{
5890 spv::Id boolTypeId = builder.makeBoolType();
5891
5892 // emit left operand
5893 builder.clearAccessChain();
5894 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005895 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005896
5897 // Operands to accumulate OpPhi operands
5898 std::vector<spv::Id> phiOperands;
5899 // accumulate left operand's phi information
5900 phiOperands.push_back(leftId);
5901 phiOperands.push_back(builder.getBuildPoint()->getId());
5902
5903 // Make the two kinds of operation symmetric with a "!"
5904 // || => emit "if (! left) result = right"
5905 // && => emit "if ( left) result = right"
5906 //
5907 // TODO: this runtime "not" for || could be avoided by adding functionality
5908 // to 'builder' to have an "else" without an "then"
5909 if (op == glslang::EOpLogicalOr)
5910 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5911
5912 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005913 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005914
5915 // emit right operand as the "then" part of the "if"
5916 builder.clearAccessChain();
5917 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005918 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005919
5920 // accumulate left operand's phi information
5921 phiOperands.push_back(rightId);
5922 phiOperands.push_back(builder.getBuildPoint()->getId());
5923
5924 // finish the "if"
5925 ifBuilder.makeEndIf();
5926
5927 // phi together the two results
5928 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5929}
5930
Rex Xu9d93a232016-05-05 12:30:44 +08005931// Return type Id of the imported set of extended instructions corresponds to the name.
5932// Import this set if it has not been imported yet.
5933spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5934{
5935 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5936 return extBuiltinMap[name];
5937 else {
Rex Xu51596642016-09-21 18:56:12 +08005938 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005939 spv::Id extBuiltins = builder.import(name);
5940 extBuiltinMap[name] = extBuiltins;
5941 return extBuiltins;
5942 }
5943}
5944
John Kessenich140f3df2015-06-26 16:58:36 -06005945}; // end anonymous namespace
5946
5947namespace glslang {
5948
John Kessenich68d78fd2015-07-12 19:28:10 -06005949void GetSpirvVersion(std::string& version)
5950{
John Kessenich9e55f632015-07-15 10:03:39 -06005951 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005952 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005953 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005954 version = buf;
5955}
5956
John Kessenicha372a3e2017-11-02 22:32:14 -06005957// For low-order part of the generator's magic number. Bump up
5958// when there is a change in the style (e.g., if SSA form changes,
5959// or a different instruction sequence to do something gets used).
5960int GetSpirvGeneratorVersion()
5961{
5962 return 2;
5963}
5964
John Kessenich140f3df2015-06-26 16:58:36 -06005965// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005966void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005967{
5968 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005969 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005970 if (out.fail())
5971 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005972 for (int i = 0; i < (int)spirv.size(); ++i) {
5973 unsigned int word = spirv[i];
5974 out.write((const char*)&word, 4);
5975 }
5976 out.close();
5977}
5978
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005979// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005980void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005981{
5982 std::ofstream out;
5983 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005984 if (out.fail())
5985 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005986 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005987 if (varName != nullptr) {
5988 out << "\t #pragma once" << std::endl;
5989 out << "const uint32_t " << varName << "[] = {" << std::endl;
5990 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005991 const int WORDS_PER_LINE = 8;
5992 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5993 out << "\t";
5994 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5995 const unsigned int word = spirv[i + j];
5996 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5997 if (i + j + 1 < (int)spirv.size()) {
5998 out << ",";
5999 }
6000 }
6001 out << std::endl;
6002 }
Flavio15017db2017-02-15 14:29:33 -08006003 if (varName != nullptr) {
6004 out << "};";
6005 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006006 out.close();
6007}
6008
GregFcd1f1692017-09-21 18:40:22 -06006009#ifdef ENABLE_OPT
6010void errHandler(const std::string& str) {
6011 std::cerr << str << std::endl;
6012}
6013#endif
6014
John Kessenich140f3df2015-06-26 16:58:36 -06006015//
6016// Set up the glslang traversal
6017//
John Kessenich121853f2017-05-31 17:11:16 -06006018void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006019{
Lei Zhang17535f72016-05-04 15:55:59 -04006020 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006021 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006022}
6023
John Kessenich121853f2017-05-31 17:11:16 -06006024void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6025 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006026{
John Kessenich140f3df2015-06-26 16:58:36 -06006027 TIntermNode* root = intermediate.getTreeRoot();
6028
6029 if (root == 0)
6030 return;
6031
John Kessenich121853f2017-05-31 17:11:16 -06006032 glslang::SpvOptions defaultOptions;
6033 if (options == nullptr)
6034 options = &defaultOptions;
6035
John Kessenich140f3df2015-06-26 16:58:36 -06006036 glslang::GetThreadPoolAllocator().push();
6037
John Kessenich121853f2017-05-31 17:11:16 -06006038 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006039 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006040 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006041 it.dumpSpv(spirv);
6042
GregFcd1f1692017-09-21 18:40:22 -06006043#ifdef ENABLE_OPT
6044 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6045 // eg. forward and remove memory writes of opaque types.
6046 if ((intermediate.getSource() == EShSourceHlsl ||
6047 options->optimizeSize) &&
6048 !options->disableOptimizer) {
6049 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6050
6051 spvtools::Optimizer optimizer(target_env);
6052 optimizer.SetMessageConsumer([](spv_message_level_t level,
6053 const char* source,
6054 const spv_position_t& position,
6055 const char* message) {
6056 std::cerr << StringifyMessage(level, source, position, message)
6057 << std::endl;
6058 });
6059
6060 optimizer.RegisterPass(CreateInlineExhaustivePass());
6061 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6062 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6063 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
6064 optimizer.RegisterPass(CreateInsertExtractElimPass());
6065 optimizer.RegisterPass(CreateAggressiveDCEPass());
6066 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06006067 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06006068 optimizer.RegisterPass(CreateBlockMergePass());
6069 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
6070 optimizer.RegisterPass(CreateInsertExtractElimPass());
6071 optimizer.RegisterPass(CreateAggressiveDCEPass());
6072 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6073 // if (options->optimizeSize)
6074 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6075
6076 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6077 return;
6078
6079 // Remove dead module-level objects: functions, types, vars
6080 // TODO(greg-lunarg): Switch to spirv-opt versions when available
6081 spv::spirvbin_t Remapper(0);
6082 Remapper.registerErrorHandler(errHandler);
6083 Remapper.remap(spirv, spv::spirvbin_t::DCE_ALL);
6084 }
6085#endif
6086
John Kessenich140f3df2015-06-26 16:58:36 -06006087 glslang::GetThreadPoolAllocator().pop();
6088}
6089
6090}; // end namespace glslang