blob: 576607dadcefe511d95419a224bc6b75a2b47814 [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
John Kessenich55e7d112015-11-15 21:33:39 -070081// For low-order part of the generator's magic number. Bump up
82// when there is a change in the style (e.g., if SSA form changes,
83// or a different instruction sequence to do something gets used).
84const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060085
qining4c912612016-04-01 10:35:16 -040086namespace {
87class SpecConstantOpModeGuard {
88public:
89 SpecConstantOpModeGuard(spv::Builder* builder)
90 : builder_(builder) {
91 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040092 }
93 ~SpecConstantOpModeGuard() {
94 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
95 : builder_->setToNormalCodeGenMode();
96 }
qining40887662016-04-03 22:20:42 -040097 void turnOnSpecConstantOpMode() {
98 builder_->setToSpecConstCodeGenMode();
99 }
qining4c912612016-04-01 10:35:16 -0400100
101private:
102 spv::Builder* builder_;
103 bool previous_flag_;
104};
105}
106
John Kessenich140f3df2015-06-26 16:58:36 -0600107//
108// The main holder of information for translating glslang to SPIR-V.
109//
110// Derives from the AST walking base class.
111//
112class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
113public:
John Kessenich121853f2017-05-31 17:11:16 -0600114 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger, glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700115 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600116
117 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
118 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
119 void visitConstantUnion(glslang::TIntermConstantUnion*);
120 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
121 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
122 void visitSymbol(glslang::TIntermSymbol* symbol);
123 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
124 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
125 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
126
John Kessenichfca82622016-11-26 13:23:20 -0700127 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700128 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600129
130protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800131 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800132 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100133 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700134 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
Rex Xu57e65922017-07-04 23:23:40 +0800135 spv::SelectionControlMask TranslateSelectionControl(glslang::TSelectionControl) const;
steve-lunargf1709e72017-05-02 20:14:50 -0600136 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600137 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600138 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
139 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600140 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
141 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
142 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600143 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700144 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600145 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600146 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
147 glslang::TLayoutPacking, const glslang::TQualifier&);
148 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
149 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700150 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700151 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800152 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600153 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700154 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700155 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
156 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
157 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 +0100158 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600159
John Kessenich6fccb3c2016-09-19 16:01:41 -0600160 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600161 void makeFunctions(const glslang::TIntermSequence&);
162 void makeGlobalInitializers(const glslang::TIntermSequence&);
163 void visitFunctions(const glslang::TIntermSequence&);
164 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800165 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600166 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
167 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
169
qining25262b32016-05-06 17:25:16 -0400170 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);
171 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
172 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 +0800173 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 +0800174 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 -0600175 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800176 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 +0800177 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800178 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600179 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 +0800180 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600181 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
182 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700183 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600184 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700185 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400186 spv::Id createSpvConstant(const glslang::TIntermTyped&);
187 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600188 bool isTrivialLeaf(const glslang::TIntermTyped* node);
189 bool isTrivial(const glslang::TIntermTyped* node);
190 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800191 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600192
John Kessenich121853f2017-05-31 17:11:16 -0600193 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600194 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600195 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700196 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600197 int sequenceDepth;
198
Lei Zhang17535f72016-05-04 15:55:59 -0400199 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400200
John Kessenich140f3df2015-06-26 16:58:36 -0600201 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
202 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700203 bool inEntryPoint;
204 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700205 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 -0700206 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600207 const glslang::TIntermediate* glslangIntermediate;
208 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800209 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600210
John Kessenich2f273362015-07-18 22:34:27 -0600211 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600212 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600213 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700214 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600215 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 -0600216 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600217};
218
219//
220// Helper functions for translating glslang representations to SPIR-V enumerants.
221//
222
223// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700224spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600225{
John Kessenich66e2faf2016-03-12 18:34:36 -0700226 switch (source) {
227 case glslang::EShSourceGlsl:
228 switch (profile) {
229 case ENoProfile:
230 case ECoreProfile:
231 case ECompatibilityProfile:
232 return spv::SourceLanguageGLSL;
233 case EEsProfile:
234 return spv::SourceLanguageESSL;
235 default:
236 return spv::SourceLanguageUnknown;
237 }
238 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600239 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600240 default:
241 return spv::SourceLanguageUnknown;
242 }
243}
244
245// Translate glslang language (stage) to SPIR-V execution model.
246spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
247{
248 switch (stage) {
249 case EShLangVertex: return spv::ExecutionModelVertex;
250 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
251 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
252 case EShLangGeometry: return spv::ExecutionModelGeometry;
253 case EShLangFragment: return spv::ExecutionModelFragment;
254 case EShLangCompute: return spv::ExecutionModelGLCompute;
255 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700256 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600257 return spv::ExecutionModelFragment;
258 }
259}
260
John Kessenich140f3df2015-06-26 16:58:36 -0600261// Translate glslang sampler type to SPIR-V dimensionality.
262spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
263{
264 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700265 case glslang::Esd1D: return spv::Dim1D;
266 case glslang::Esd2D: return spv::Dim2D;
267 case glslang::Esd3D: return spv::Dim3D;
268 case glslang::EsdCube: return spv::DimCube;
269 case glslang::EsdRect: return spv::DimRect;
270 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700271 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600272 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700273 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600274 return spv::Dim2D;
275 }
276}
277
John Kessenichf6640762016-08-01 19:44:00 -0600278// Translate glslang precision to SPIR-V precision decorations.
279spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600280{
John Kessenichf6640762016-08-01 19:44:00 -0600281 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700282 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600283 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600284 default:
285 return spv::NoPrecision;
286 }
287}
288
John Kessenichf6640762016-08-01 19:44:00 -0600289// Translate glslang type to SPIR-V precision decorations.
290spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
291{
292 return TranslatePrecisionDecoration(type.getQualifier().precision);
293}
294
John Kessenich140f3df2015-06-26 16:58:36 -0600295// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600296spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600297{
298 if (type.getBasicType() == glslang::EbtBlock) {
299 switch (type.getQualifier().storage) {
300 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600301 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600302 case glslang::EvqVaryingIn: return spv::DecorationBlock;
303 case glslang::EvqVaryingOut: return spv::DecorationBlock;
304 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700305 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600306 break;
307 }
308 }
309
John Kessenich4016e382016-07-15 11:53:56 -0600310 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600311}
312
Rex Xu1da878f2016-02-21 20:59:01 +0800313// Translate glslang type to SPIR-V memory decorations.
314void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
315{
316 if (qualifier.coherent)
317 memory.push_back(spv::DecorationCoherent);
318 if (qualifier.volatil)
319 memory.push_back(spv::DecorationVolatile);
320 if (qualifier.restrict)
321 memory.push_back(spv::DecorationRestrict);
322 if (qualifier.readonly)
323 memory.push_back(spv::DecorationNonWritable);
324 if (qualifier.writeonly)
325 memory.push_back(spv::DecorationNonReadable);
326}
327
John Kessenich140f3df2015-06-26 16:58:36 -0600328// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700329spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600330{
331 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700332 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600333 case glslang::ElmRowMajor:
334 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700335 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600336 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700337 default:
338 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600339 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600340 }
341 } else {
342 switch (type.getBasicType()) {
343 default:
John Kessenich4016e382016-07-15 11:53:56 -0600344 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600345 break;
346 case glslang::EbtBlock:
347 switch (type.getQualifier().storage) {
348 case glslang::EvqUniform:
349 case glslang::EvqBuffer:
350 switch (type.getQualifier().layoutPacking) {
351 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600352 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
353 default:
John Kessenich4016e382016-07-15 11:53:56 -0600354 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600355 }
356 case glslang::EvqVaryingIn:
357 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700358 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600359 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600360 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700361 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600362 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600363 }
364 }
365 }
366}
367
368// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600369// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700370// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800371spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600372{
Rex Xubbceed72016-05-21 09:40:44 +0800373 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700374 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600375 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800376 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700377 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700378 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600379 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800380#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800381 else if (qualifier.explicitInterp) {
382 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800383 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800384 }
Rex Xu9d93a232016-05-05 12:30:44 +0800385#endif
Rex Xubbceed72016-05-21 09:40:44 +0800386 else
John Kessenich4016e382016-07-15 11:53:56 -0600387 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800388}
389
390// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600391// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800392// should be applied.
393spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
394{
395 if (qualifier.patch)
396 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700397 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600398 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700399 else if (qualifier.sample) {
400 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600401 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700402 } else
John Kessenich4016e382016-07-15 11:53:56 -0600403 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600404}
405
John Kessenich92187592016-02-01 13:45:25 -0700406// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700407spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600408{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700409 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600410 return spv::DecorationInvariant;
411 else
John Kessenich4016e382016-07-15 11:53:56 -0600412 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600413}
414
qining9220dbb2016-05-04 17:34:38 -0400415// If glslang type is noContraction, return SPIR-V NoContraction decoration.
416spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
417{
418 if (qualifier.noContraction)
419 return spv::DecorationNoContraction;
420 else
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400422}
423
David Netoa901ffe2016-06-08 14:11:40 +0100424// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
425// associated capabilities when required. For some built-in variables, a capability
426// is generated only when using the variable in an executable instruction, but not when
427// just declaring a struct member variable with it. This is true for PointSize,
428// ClipDistance, and CullDistance.
429spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600430{
431 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700432 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600433 // Defer adding the capability until the built-in is actually used.
434 if (! memberDeclaration) {
435 switch (glslangIntermediate->getStage()) {
436 case EShLangGeometry:
437 builder.addCapability(spv::CapabilityGeometryPointSize);
438 break;
439 case EShLangTessControl:
440 case EShLangTessEvaluation:
441 builder.addCapability(spv::CapabilityTessellationPointSize);
442 break;
443 default:
444 break;
445 }
John Kessenich92187592016-02-01 13:45:25 -0700446 }
447 return spv::BuiltInPointSize;
448
John Kessenichebb50532016-05-16 19:22:05 -0600449 // These *Distance capabilities logically belong here, but if the member is declared and
450 // then never used, consumers of SPIR-V prefer the capability not be declared.
451 // They are now generated when used, rather than here when declared.
452 // Potentially, the specification should be more clear what the minimum
453 // use needed is to trigger the capability.
454 //
John Kessenich92187592016-02-01 13:45:25 -0700455 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100456 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800457 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700458 return spv::BuiltInClipDistance;
459
460 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100461 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800462 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700463 return spv::BuiltInCullDistance;
464
465 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600466 builder.addCapability(spv::CapabilityMultiViewport);
467 if (glslangIntermediate->getStage() == EShLangVertex ||
468 glslangIntermediate->getStage() == EShLangTessControl ||
469 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800470
John Kessenichba6a3c22017-09-13 13:22:50 -0600471 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
472 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800473 }
John Kessenich92187592016-02-01 13:45:25 -0700474 return spv::BuiltInViewportIndex;
475
John Kessenich5e801132016-02-15 11:09:46 -0700476 case glslang::EbvSampleId:
477 builder.addCapability(spv::CapabilitySampleRateShading);
478 return spv::BuiltInSampleId;
479
480 case glslang::EbvSamplePosition:
481 builder.addCapability(spv::CapabilitySampleRateShading);
482 return spv::BuiltInSamplePosition;
483
484 case glslang::EbvSampleMask:
485 builder.addCapability(spv::CapabilitySampleRateShading);
486 return spv::BuiltInSampleMask;
487
John Kessenich78a45572016-07-08 14:05:15 -0600488 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600489 builder.addCapability(spv::CapabilityGeometry);
490 if (glslangIntermediate->getStage() == EShLangVertex ||
491 glslangIntermediate->getStage() == EShLangTessControl ||
492 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800493
John Kessenichba6a3c22017-09-13 13:22:50 -0600494 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
495 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800496 }
John Kessenich78a45572016-07-08 14:05:15 -0600497 return spv::BuiltInLayer;
498
John Kessenich140f3df2015-06-26 16:58:36 -0600499 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600500 case glslang::EbvVertexId: return spv::BuiltInVertexId;
501 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700502 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
503 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800504
John Kessenichda581a22015-10-14 14:10:30 -0600505 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800506 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
507 builder.addCapability(spv::CapabilityDrawParameters);
508 return spv::BuiltInBaseVertex;
509
John Kessenichda581a22015-10-14 14:10:30 -0600510 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800511 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
512 builder.addCapability(spv::CapabilityDrawParameters);
513 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200514
John Kessenichda581a22015-10-14 14:10:30 -0600515 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800516 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
517 builder.addCapability(spv::CapabilityDrawParameters);
518 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200519
520 case glslang::EbvPrimitiveId:
521 if (glslangIntermediate->getStage() == EShLangFragment)
522 builder.addCapability(spv::CapabilityGeometry);
523 return spv::BuiltInPrimitiveId;
524
Rex Xu37cdcee2017-06-29 17:46:34 +0800525 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800526 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
527 builder.addCapability(spv::CapabilityStencilExportEXT);
528 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800529
John Kessenich140f3df2015-06-26 16:58:36 -0600530 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600531 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
532 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
533 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
534 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
535 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
536 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
537 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600538 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
539 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
540 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
541 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
542 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
543 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
544 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
545 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800546
Rex Xu574ab042016-04-14 16:53:07 +0800547 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800548 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800549 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
550 return spv::BuiltInSubgroupSize;
551
Rex Xu574ab042016-04-14 16:53:07 +0800552 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800553 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800554 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
555 return spv::BuiltInSubgroupLocalInvocationId;
556
Rex Xu574ab042016-04-14 16:53:07 +0800557 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800558 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
559 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
560 return spv::BuiltInSubgroupEqMaskKHR;
561
Rex Xu574ab042016-04-14 16:53:07 +0800562 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800563 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
564 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
565 return spv::BuiltInSubgroupGeMaskKHR;
566
Rex Xu574ab042016-04-14 16:53:07 +0800567 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800568 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
569 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
570 return spv::BuiltInSubgroupGtMaskKHR;
571
Rex Xu574ab042016-04-14 16:53:07 +0800572 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800573 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
574 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
575 return spv::BuiltInSubgroupLeMaskKHR;
576
Rex Xu574ab042016-04-14 16:53:07 +0800577 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800578 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
579 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
580 return spv::BuiltInSubgroupLtMaskKHR;
581
Rex Xu9d93a232016-05-05 12:30:44 +0800582#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800583 case glslang::EbvBaryCoordNoPersp:
584 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
585 return spv::BuiltInBaryCoordNoPerspAMD;
586
587 case glslang::EbvBaryCoordNoPerspCentroid:
588 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
589 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
590
591 case glslang::EbvBaryCoordNoPerspSample:
592 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
593 return spv::BuiltInBaryCoordNoPerspSampleAMD;
594
595 case glslang::EbvBaryCoordSmooth:
596 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
597 return spv::BuiltInBaryCoordSmoothAMD;
598
599 case glslang::EbvBaryCoordSmoothCentroid:
600 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
601 return spv::BuiltInBaryCoordSmoothCentroidAMD;
602
603 case glslang::EbvBaryCoordSmoothSample:
604 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
605 return spv::BuiltInBaryCoordSmoothSampleAMD;
606
607 case glslang::EbvBaryCoordPullModel:
608 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
609 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800610#endif
chaoc771d89f2017-01-13 01:10:53 -0800611
John Kessenich6c8aaac2017-02-27 01:20:51 -0700612 case glslang::EbvDeviceIndex:
613 builder.addExtension(spv::E_SPV_KHR_device_group);
614 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700615 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700616
617 case glslang::EbvViewIndex:
618 builder.addExtension(spv::E_SPV_KHR_multiview);
619 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700620 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700621
chaoc771d89f2017-01-13 01:10:53 -0800622#ifdef NV_EXTENSIONS
623 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800624 if (!memberDeclaration) {
625 builder.addExtension(spv::E_SPV_NV_viewport_array2);
626 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
627 }
chaoc771d89f2017-01-13 01:10:53 -0800628 return spv::BuiltInViewportMaskNV;
629 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800630 if (!memberDeclaration) {
631 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
632 builder.addCapability(spv::CapabilityShaderStereoViewNV);
633 }
chaoc771d89f2017-01-13 01:10:53 -0800634 return spv::BuiltInSecondaryPositionNV;
635 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800636 if (!memberDeclaration) {
637 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
638 builder.addCapability(spv::CapabilityShaderStereoViewNV);
639 }
chaoc771d89f2017-01-13 01:10:53 -0800640 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800641 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800642 if (!memberDeclaration) {
643 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
644 builder.addCapability(spv::CapabilityPerViewAttributesNV);
645 }
chaocdf3956c2017-02-14 14:52:34 -0800646 return spv::BuiltInPositionPerViewNV;
647 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800648 if (!memberDeclaration) {
649 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
650 builder.addCapability(spv::CapabilityPerViewAttributesNV);
651 }
chaocdf3956c2017-02-14 14:52:34 -0800652 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800653#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800654 default:
655 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600656 }
657}
658
Rex Xufc618912015-09-09 16:42:49 +0800659// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700660spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800661{
662 assert(type.getBasicType() == glslang::EbtSampler);
663
John Kessenich5d0fa972016-02-15 11:57:00 -0700664 // Check for capabilities
665 switch (type.getQualifier().layoutFormat) {
666 case glslang::ElfRg32f:
667 case glslang::ElfRg16f:
668 case glslang::ElfR11fG11fB10f:
669 case glslang::ElfR16f:
670 case glslang::ElfRgba16:
671 case glslang::ElfRgb10A2:
672 case glslang::ElfRg16:
673 case glslang::ElfRg8:
674 case glslang::ElfR16:
675 case glslang::ElfR8:
676 case glslang::ElfRgba16Snorm:
677 case glslang::ElfRg16Snorm:
678 case glslang::ElfRg8Snorm:
679 case glslang::ElfR16Snorm:
680 case glslang::ElfR8Snorm:
681
682 case glslang::ElfRg32i:
683 case glslang::ElfRg16i:
684 case glslang::ElfRg8i:
685 case glslang::ElfR16i:
686 case glslang::ElfR8i:
687
688 case glslang::ElfRgb10a2ui:
689 case glslang::ElfRg32ui:
690 case glslang::ElfRg16ui:
691 case glslang::ElfRg8ui:
692 case glslang::ElfR16ui:
693 case glslang::ElfR8ui:
694 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
695 break;
696
697 default:
698 break;
699 }
700
701 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800702 switch (type.getQualifier().layoutFormat) {
703 case glslang::ElfNone: return spv::ImageFormatUnknown;
704 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
705 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
706 case glslang::ElfR32f: return spv::ImageFormatR32f;
707 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
708 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
709 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
710 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
711 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
712 case glslang::ElfR16f: return spv::ImageFormatR16f;
713 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
714 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
715 case glslang::ElfRg16: return spv::ImageFormatRg16;
716 case glslang::ElfRg8: return spv::ImageFormatRg8;
717 case glslang::ElfR16: return spv::ImageFormatR16;
718 case glslang::ElfR8: return spv::ImageFormatR8;
719 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
720 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
721 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
722 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
723 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
724 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
725 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
726 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
727 case glslang::ElfR32i: return spv::ImageFormatR32i;
728 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
729 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
730 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
731 case glslang::ElfR16i: return spv::ImageFormatR16i;
732 case glslang::ElfR8i: return spv::ImageFormatR8i;
733 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
734 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
735 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
736 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
737 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
738 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
739 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
740 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
741 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
742 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600743 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800744 }
745}
746
Rex Xu57e65922017-07-04 23:23:40 +0800747spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
748{
749 switch (selectionControl) {
750 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
751 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
752 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
753 default: return spv::SelectionControlMaskNone;
754 }
755}
756
steve-lunargf1709e72017-05-02 20:14:50 -0600757spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
758{
759 switch (loopControl) {
760 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
761 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
762 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
763 // TODO: DependencyInfinite
764 // TODO: DependencyLength
765 default: return spv::LoopControlMaskNone;
766 }
767}
768
John Kessenicha5c5fb62017-05-05 05:09:58 -0600769// Translate glslang type to SPIR-V storage class.
770spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
771{
772 if (type.getQualifier().isPipeInput())
773 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600774 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600775 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600776
777 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
778 type.getQualifier().storage == glslang::EvqUniform) {
779 if (type.getBasicType() == glslang::EbtAtomicUint)
780 return spv::StorageClassAtomicCounter;
781 if (type.containsOpaque())
782 return spv::StorageClassUniformConstant;
783 }
784
785 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600786 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
787 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600788 }
789
790 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600791 if (type.getQualifier().layoutPushConstant)
792 return spv::StorageClassPushConstant;
793 if (type.getBasicType() == glslang::EbtBlock)
794 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600795 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600796 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600797
798 switch (type.getQualifier().storage) {
799 case glslang::EvqShared: return spv::StorageClassWorkgroup;
800 case glslang::EvqGlobal: return spv::StorageClassPrivate;
801 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
802 case glslang::EvqTemporary: return spv::StorageClassFunction;
803 default:
804 assert(0);
805 break;
806 }
807
808 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600809}
810
qining25262b32016-05-06 17:25:16 -0400811// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700812// descriptor set.
813bool IsDescriptorResource(const glslang::TType& type)
814{
John Kessenichf7497e22016-03-08 21:36:22 -0700815 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700816 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700817 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700818
819 // non block...
820 // basically samplerXXX/subpass/sampler/texture are all included
821 // if they are the global-scope-class, not the function parameter
822 // (or local, if they ever exist) class.
823 if (type.getBasicType() == glslang::EbtSampler)
824 return type.getQualifier().isUniformOrBuffer();
825
826 // None of the above.
827 return false;
828}
829
John Kesseniche0b6cad2015-12-24 10:30:13 -0700830void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
831{
832 if (child.layoutMatrix == glslang::ElmNone)
833 child.layoutMatrix = parent.layoutMatrix;
834
835 if (parent.invariant)
836 child.invariant = true;
837 if (parent.nopersp)
838 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800839#ifdef AMD_EXTENSIONS
840 if (parent.explicitInterp)
841 child.explicitInterp = true;
842#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700843 if (parent.flat)
844 child.flat = true;
845 if (parent.centroid)
846 child.centroid = true;
847 if (parent.patch)
848 child.patch = true;
849 if (parent.sample)
850 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800851 if (parent.coherent)
852 child.coherent = true;
853 if (parent.volatil)
854 child.volatil = true;
855 if (parent.restrict)
856 child.restrict = true;
857 if (parent.readonly)
858 child.readonly = true;
859 if (parent.writeonly)
860 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700861}
862
John Kessenichf2b7f332016-09-01 17:05:23 -0600863bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700864{
John Kessenich7b9fa252016-01-21 18:56:57 -0700865 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600866 // - struct members might inherit from a struct declaration
867 // (note that non-block structs don't explicitly inherit,
868 // only implicitly, meaning no decoration involved)
869 // - affect decorations on the struct members
870 // (note smooth does not, and expecting something like volatile
871 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700872 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600873 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700874}
875
John Kessenich140f3df2015-06-26 16:58:36 -0600876//
877// Implement the TGlslangToSpvTraverser class.
878//
879
John Kessenich121853f2017-05-31 17:11:16 -0600880TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
881 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
882 : TIntermTraverser(true, false, true),
883 options(options),
884 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600885 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400886 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700887 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600888 glslangIntermediate(glslangIntermediate)
889{
890 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
891
892 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600893 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
894 glslangIntermediate->getVersion());
895
John Kessenich121853f2017-05-31 17:11:16 -0600896 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600897 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600898 builder.setSourceFile(glslangIntermediate->getSourceFile());
899
900 // Set the source shader's text. If for SPV version 1.0, include
901 // a preamble in comments stating the OpModuleProcessed instructions.
902 // Otherwise, emit those as actual instructions.
903 std::string text;
904 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
905 for (int p = 0; p < (int)processes.size(); ++p) {
906 if (glslangIntermediate->getSpv().spv < 0x00010100) {
907 text.append("// OpModuleProcessed ");
908 text.append(processes[p]);
909 text.append("\n");
910 } else
911 builder.addModuleProcessed(processes[p]);
912 }
913 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
914 text.append("#line 1\n");
915 text.append(glslangIntermediate->getSourceText());
916 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600917 }
John Kessenich140f3df2015-06-26 16:58:36 -0600918 stdBuiltins = builder.import("GLSL.std.450");
919 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600920 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
921 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600922
923 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600924 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
925 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600926 builder.addSourceExtension(it->c_str());
927
928 // Add the top-level modes for this shader.
929
John Kessenich92187592016-02-01 13:45:25 -0700930 if (glslangIntermediate->getXfbMode()) {
931 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600932 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700933 }
John Kessenich140f3df2015-06-26 16:58:36 -0600934
935 unsigned int mode;
936 switch (glslangIntermediate->getStage()) {
937 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600938 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600939 break;
940
steve-lunarge7412492017-03-23 11:56:07 -0600941 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600942 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600943 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600944
steve-lunarge7412492017-03-23 11:56:07 -0600945 glslang::TLayoutGeometry primitive;
946
947 if (glslangIntermediate->getStage() == EShLangTessControl) {
948 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
949 primitive = glslangIntermediate->getOutputPrimitive();
950 } else {
951 primitive = glslangIntermediate->getInputPrimitive();
952 }
953
954 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700955 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
956 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
957 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600958 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600959 }
John Kessenich4016e382016-07-15 11:53:56 -0600960 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600961 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
962
John Kesseniche6903322015-10-13 16:29:02 -0600963 switch (glslangIntermediate->getVertexSpacing()) {
964 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
965 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
966 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600967 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600968 }
John Kessenich4016e382016-07-15 11:53:56 -0600969 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600970 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
971
972 switch (glslangIntermediate->getVertexOrder()) {
973 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
974 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600975 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600976 }
John Kessenich4016e382016-07-15 11:53:56 -0600977 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600978 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
979
980 if (glslangIntermediate->getPointMode())
981 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600982 break;
983
984 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600985 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600986 switch (glslangIntermediate->getInputPrimitive()) {
987 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
988 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
989 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700990 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600991 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600992 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600993 }
John Kessenich4016e382016-07-15 11:53:56 -0600994 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600995 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600996
John Kessenich140f3df2015-06-26 16:58:36 -0600997 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
998
999 switch (glslangIntermediate->getOutputPrimitive()) {
1000 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1001 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1002 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001003 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001004 }
John Kessenich4016e382016-07-15 11:53:56 -06001005 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001006 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1007 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1008 break;
1009
1010 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001011 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001012 if (glslangIntermediate->getPixelCenterInteger())
1013 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001014
John Kessenich140f3df2015-06-26 16:58:36 -06001015 if (glslangIntermediate->getOriginUpperLeft())
1016 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001017 else
1018 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001019
1020 if (glslangIntermediate->getEarlyFragmentTests())
1021 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1022
chaocc1204522017-06-30 17:14:30 -07001023 if (glslangIntermediate->getPostDepthCoverage()) {
1024 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1025 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1026 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1027 }
1028
John Kesseniche6903322015-10-13 16:29:02 -06001029 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001030 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1031 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001032 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001033 }
John Kessenich4016e382016-07-15 11:53:56 -06001034 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001035 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1036
1037 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1038 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001039 break;
1040
1041 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001042 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001043 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1044 glslangIntermediate->getLocalSize(1),
1045 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001046 break;
1047
1048 default:
1049 break;
1050 }
John Kessenich140f3df2015-06-26 16:58:36 -06001051}
1052
John Kessenichfca82622016-11-26 13:23:20 -07001053// Finish creating SPV, after the traversal is complete.
1054void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001055{
John Kessenich517fe7a2016-11-26 13:31:47 -07001056 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001057 builder.setBuildPoint(shaderEntry->getLastBlock());
1058 builder.leaveFunction();
1059 }
1060
John Kessenich7ba63412015-12-20 17:37:07 -07001061 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001062 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1063 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001064
qiningda397332016-03-09 19:54:03 -05001065 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001066}
1067
John Kessenichfca82622016-11-26 13:23:20 -07001068// Write the SPV into 'out'.
1069void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001070{
John Kessenichfca82622016-11-26 13:23:20 -07001071 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001072}
1073
1074//
1075// Implement the traversal functions.
1076//
1077// Return true from interior nodes to have the external traversal
1078// continue on to children. Return false if children were
1079// already processed.
1080//
1081
1082//
qining25262b32016-05-06 17:25:16 -04001083// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001084// - uniform/input reads
1085// - output writes
1086// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1087// - something simple that degenerates into the last bullet
1088//
1089void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1090{
qining75d1d802016-04-06 14:42:01 -04001091 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1092 if (symbol->getType().getQualifier().isSpecConstant())
1093 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1094
John Kessenich140f3df2015-06-26 16:58:36 -06001095 // getSymbolId() will set up all the IO decorations on the first call.
1096 // Formal function parameters were mapped during makeFunctions().
1097 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001098
1099 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1100 if (builder.isPointer(id)) {
1101 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001102 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1103 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1104 iOSet.insert(id);
1105 }
John Kessenich7ba63412015-12-20 17:37:07 -07001106 }
1107
1108 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001109 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001110 // Prepare to generate code for the access
1111
1112 // L-value chains will be computed left to right. We're on the symbol now,
1113 // which is the left-most part of the access chain, so now is "clear" time,
1114 // followed by setting the base.
1115 builder.clearAccessChain();
1116
1117 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001118 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001119 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001120 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001121 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001122 // These are also pure R-values.
1123 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001124 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001125 builder.setAccessChainRValue(id);
1126 else
1127 builder.setAccessChainLValue(id);
1128 }
1129}
1130
1131bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1132{
John Kesseniche485c7a2017-05-31 18:50:53 -06001133 builder.setLine(node->getLoc().line);
1134
qining40887662016-04-03 22:20:42 -04001135 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1136 if (node->getType().getQualifier().isSpecConstant())
1137 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1138
John Kessenich140f3df2015-06-26 16:58:36 -06001139 // First, handle special cases
1140 switch (node->getOp()) {
1141 case glslang::EOpAssign:
1142 case glslang::EOpAddAssign:
1143 case glslang::EOpSubAssign:
1144 case glslang::EOpMulAssign:
1145 case glslang::EOpVectorTimesMatrixAssign:
1146 case glslang::EOpVectorTimesScalarAssign:
1147 case glslang::EOpMatrixTimesScalarAssign:
1148 case glslang::EOpMatrixTimesMatrixAssign:
1149 case glslang::EOpDivAssign:
1150 case glslang::EOpModAssign:
1151 case glslang::EOpAndAssign:
1152 case glslang::EOpInclusiveOrAssign:
1153 case glslang::EOpExclusiveOrAssign:
1154 case glslang::EOpLeftShiftAssign:
1155 case glslang::EOpRightShiftAssign:
1156 // A bin-op assign "a += b" means the same thing as "a = a + b"
1157 // where a is evaluated before b. For a simple assignment, GLSL
1158 // says to evaluate the left before the right. So, always, left
1159 // node then right node.
1160 {
1161 // get the left l-value, save it away
1162 builder.clearAccessChain();
1163 node->getLeft()->traverse(this);
1164 spv::Builder::AccessChain lValue = builder.getAccessChain();
1165
1166 // evaluate the right
1167 builder.clearAccessChain();
1168 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001169 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001170
1171 if (node->getOp() != glslang::EOpAssign) {
1172 // the left is also an r-value
1173 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001174 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001175
1176 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001177 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001178 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001179 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1180 node->getType().getBasicType());
1181
1182 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001183 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001184 }
1185
1186 // store the result
1187 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001188 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001189
1190 // assignments are expressions having an rValue after they are evaluated...
1191 builder.clearAccessChain();
1192 builder.setAccessChainRValue(rValue);
1193 }
1194 return false;
1195 case glslang::EOpIndexDirect:
1196 case glslang::EOpIndexDirectStruct:
1197 {
1198 // Get the left part of the access chain.
1199 node->getLeft()->traverse(this);
1200
1201 // Add the next element in the chain
1202
David Netoa901ffe2016-06-08 14:11:40 +01001203 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001204 if (! node->getLeft()->getType().isArray() &&
1205 node->getLeft()->getType().isVector() &&
1206 node->getOp() == glslang::EOpIndexDirect) {
1207 // This is essentially a hard-coded vector swizzle of size 1,
1208 // so short circuit the access-chain stuff with a swizzle.
1209 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001210 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001211 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001212 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001213 int spvIndex = glslangIndex;
1214 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1215 node->getOp() == glslang::EOpIndexDirectStruct)
1216 {
1217 // This may be, e.g., an anonymous block-member selection, which generally need
1218 // index remapping due to hidden members in anonymous blocks.
1219 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1220 assert(remapper.size() > 0);
1221 spvIndex = remapper[glslangIndex];
1222 }
John Kessenichebb50532016-05-16 19:22:05 -06001223
David Netoa901ffe2016-06-08 14:11:40 +01001224 // normal case for indexing array or structure or block
1225 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1226
1227 // Add capabilities here for accessing PointSize and clip/cull distance.
1228 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001229 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001230 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001231 }
1232 }
1233 return false;
1234 case glslang::EOpIndexIndirect:
1235 {
1236 // Structure or array or vector indirection.
1237 // Will use native SPIR-V access-chain for struct and array indirection;
1238 // matrices are arrays of vectors, so will also work for a matrix.
1239 // Will use the access chain's 'component' for variable index into a vector.
1240
1241 // This adapter is building access chains left to right.
1242 // Set up the access chain to the left.
1243 node->getLeft()->traverse(this);
1244
1245 // save it so that computing the right side doesn't trash it
1246 spv::Builder::AccessChain partial = builder.getAccessChain();
1247
1248 // compute the next index in the chain
1249 builder.clearAccessChain();
1250 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001251 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001252
1253 // restore the saved access chain
1254 builder.setAccessChain(partial);
1255
1256 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001257 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001258 else
John Kessenichfa668da2015-09-13 14:46:30 -06001259 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001260 }
1261 return false;
1262 case glslang::EOpVectorSwizzle:
1263 {
1264 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001265 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001266 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001267 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001268 }
1269 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001270 case glslang::EOpMatrixSwizzle:
1271 logger->missingFunctionality("matrix swizzle");
1272 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001273 case glslang::EOpLogicalOr:
1274 case glslang::EOpLogicalAnd:
1275 {
1276
1277 // These may require short circuiting, but can sometimes be done as straight
1278 // binary operations. The right operand must be short circuited if it has
1279 // side effects, and should probably be if it is complex.
1280 if (isTrivial(node->getRight()->getAsTyped()))
1281 break; // handle below as a normal binary operation
1282 // otherwise, we need to do dynamic short circuiting on the right operand
1283 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1284 builder.clearAccessChain();
1285 builder.setAccessChainRValue(result);
1286 }
1287 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001288 default:
1289 break;
1290 }
1291
1292 // Assume generic binary op...
1293
John Kessenich32cfd492016-02-02 12:37:46 -07001294 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001295 builder.clearAccessChain();
1296 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001297 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001298
John Kessenich32cfd492016-02-02 12:37:46 -07001299 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001300 builder.clearAccessChain();
1301 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001302 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001303
John Kessenich32cfd492016-02-02 12:37:46 -07001304 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001305 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001306 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001307 convertGlslangToSpvType(node->getType()), left, right,
1308 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001309
John Kessenich50e57562015-12-21 21:21:11 -07001310 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001311 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001312 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001313 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001314 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001315 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001316 return false;
1317 }
John Kessenich140f3df2015-06-26 16:58:36 -06001318}
1319
1320bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1321{
John Kesseniche485c7a2017-05-31 18:50:53 -06001322 builder.setLine(node->getLoc().line);
1323
qining40887662016-04-03 22:20:42 -04001324 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1325 if (node->getType().getQualifier().isSpecConstant())
1326 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1327
John Kessenichfc51d282015-08-19 13:34:18 -06001328 spv::Id result = spv::NoResult;
1329
1330 // try texturing first
1331 result = createImageTextureFunctionCall(node);
1332 if (result != spv::NoResult) {
1333 builder.clearAccessChain();
1334 builder.setAccessChainRValue(result);
1335
1336 return false; // done with this node
1337 }
1338
1339 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001340
1341 if (node->getOp() == glslang::EOpArrayLength) {
1342 // Quite special; won't want to evaluate the operand.
1343
1344 // Normal .length() would have been constant folded by the front-end.
1345 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001346 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001347 assert(node->getOperand()->getType().isRuntimeSizedArray());
1348 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1349 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001350 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1351 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001352
1353 builder.clearAccessChain();
1354 builder.setAccessChainRValue(length);
1355
1356 return false;
1357 }
1358
John Kessenichfc51d282015-08-19 13:34:18 -06001359 // Start by evaluating the operand
1360
John Kessenich8c8505c2016-07-26 12:50:38 -06001361 // Does it need a swizzle inversion? If so, evaluation is inverted;
1362 // operate first on the swizzle base, then apply the swizzle.
1363 spv::Id invertedType = spv::NoType;
1364 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1365 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1366 invertedType = getInvertedSwizzleType(*node->getOperand());
1367
John Kessenich140f3df2015-06-26 16:58:36 -06001368 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001369 if (invertedType != spv::NoType)
1370 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1371 else
1372 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001373
Rex Xufc618912015-09-09 16:42:49 +08001374 spv::Id operand = spv::NoResult;
1375
1376 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1377 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001378 node->getOp() == glslang::EOpAtomicCounter ||
1379 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001380 operand = builder.accessChainGetLValue(); // Special case l-value operands
1381 else
John Kessenich32cfd492016-02-02 12:37:46 -07001382 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001383
John Kessenichf6640762016-08-01 19:44:00 -06001384 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001385 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001386
1387 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001388 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001389 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001390
1391 // if not, then possibly an operation
1392 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001393 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001394
1395 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001396 if (invertedType)
1397 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1398
John Kessenich140f3df2015-06-26 16:58:36 -06001399 builder.clearAccessChain();
1400 builder.setAccessChainRValue(result);
1401
1402 return false; // done with this node
1403 }
1404
1405 // it must be a special case, check...
1406 switch (node->getOp()) {
1407 case glslang::EOpPostIncrement:
1408 case glslang::EOpPostDecrement:
1409 case glslang::EOpPreIncrement:
1410 case glslang::EOpPreDecrement:
1411 {
1412 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001413 spv::Id one = 0;
1414 if (node->getBasicType() == glslang::EbtFloat)
1415 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001416 else if (node->getBasicType() == glslang::EbtDouble)
1417 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001418#ifdef AMD_EXTENSIONS
1419 else if (node->getBasicType() == glslang::EbtFloat16)
1420 one = builder.makeFloat16Constant(1.0F);
1421#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001422 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1423 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001424#ifdef AMD_EXTENSIONS
1425 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1426 one = builder.makeInt16Constant(1);
1427#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001428 else
1429 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001430 glslang::TOperator op;
1431 if (node->getOp() == glslang::EOpPreIncrement ||
1432 node->getOp() == glslang::EOpPostIncrement)
1433 op = glslang::EOpAdd;
1434 else
1435 op = glslang::EOpSub;
1436
John Kessenichf6640762016-08-01 19:44:00 -06001437 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001438 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001439 convertGlslangToSpvType(node->getType()), operand, one,
1440 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001441 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001442
1443 // The result of operation is always stored, but conditionally the
1444 // consumed result. The consumed result is always an r-value.
1445 builder.accessChainStore(result);
1446 builder.clearAccessChain();
1447 if (node->getOp() == glslang::EOpPreIncrement ||
1448 node->getOp() == glslang::EOpPreDecrement)
1449 builder.setAccessChainRValue(result);
1450 else
1451 builder.setAccessChainRValue(operand);
1452 }
1453
1454 return false;
1455
1456 case glslang::EOpEmitStreamVertex:
1457 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1458 return false;
1459 case glslang::EOpEndStreamPrimitive:
1460 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1461 return false;
1462
1463 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001464 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001465 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001466 }
John Kessenich140f3df2015-06-26 16:58:36 -06001467}
1468
1469bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1470{
qining27e04a02016-04-14 16:40:20 -04001471 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1472 if (node->getType().getQualifier().isSpecConstant())
1473 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1474
John Kessenichfc51d282015-08-19 13:34:18 -06001475 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001476 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1477 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001478
1479 // try texturing
1480 result = createImageTextureFunctionCall(node);
1481 if (result != spv::NoResult) {
1482 builder.clearAccessChain();
1483 builder.setAccessChainRValue(result);
1484
1485 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001486#ifdef AMD_EXTENSIONS
1487 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1488#else
John Kessenich56bab042015-09-16 10:54:31 -06001489 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001490#endif
Rex Xufc618912015-09-09 16:42:49 +08001491 // "imageStore" is a special case, which has no result
1492 return false;
1493 }
John Kessenichfc51d282015-08-19 13:34:18 -06001494
John Kessenich140f3df2015-06-26 16:58:36 -06001495 glslang::TOperator binOp = glslang::EOpNull;
1496 bool reduceComparison = true;
1497 bool isMatrix = false;
1498 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001499 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001500
1501 assert(node->getOp());
1502
John Kessenichf6640762016-08-01 19:44:00 -06001503 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001504
1505 switch (node->getOp()) {
1506 case glslang::EOpSequence:
1507 {
1508 if (preVisit)
1509 ++sequenceDepth;
1510 else
1511 --sequenceDepth;
1512
1513 if (sequenceDepth == 1) {
1514 // If this is the parent node of all the functions, we want to see them
1515 // early, so all call points have actual SPIR-V functions to reference.
1516 // In all cases, still let the traverser visit the children for us.
1517 makeFunctions(node->getAsAggregate()->getSequence());
1518
John Kessenich6fccb3c2016-09-19 16:01:41 -06001519 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001520 // anything else gets there, so visit out of order, doing them all now.
1521 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1522
John Kessenich6a60c2f2016-12-08 21:01:59 -07001523 // 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 -06001524 // so do them manually.
1525 visitFunctions(node->getAsAggregate()->getSequence());
1526
1527 return false;
1528 }
1529
1530 return true;
1531 }
1532 case glslang::EOpLinkerObjects:
1533 {
1534 if (visit == glslang::EvPreVisit)
1535 linkageOnly = true;
1536 else
1537 linkageOnly = false;
1538
1539 return true;
1540 }
1541 case glslang::EOpComma:
1542 {
1543 // processing from left to right naturally leaves the right-most
1544 // lying around in the access chain
1545 glslang::TIntermSequence& glslangOperands = node->getSequence();
1546 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1547 glslangOperands[i]->traverse(this);
1548
1549 return false;
1550 }
1551 case glslang::EOpFunction:
1552 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001553 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001554 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001555 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001556 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001557 } else {
1558 handleFunctionEntry(node);
1559 }
1560 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001561 if (inEntryPoint)
1562 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001563 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001564 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001565 }
1566
1567 return true;
1568 case glslang::EOpParameters:
1569 // Parameters will have been consumed by EOpFunction processing, but not
1570 // the body, so we still visited the function node's children, making this
1571 // child redundant.
1572 return false;
1573 case glslang::EOpFunctionCall:
1574 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001575 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001576 if (node->isUserDefined())
1577 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001578 // 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 -07001579 if (result) {
1580 builder.clearAccessChain();
1581 builder.setAccessChainRValue(result);
1582 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001583 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001584
1585 return false;
1586 }
1587 case glslang::EOpConstructMat2x2:
1588 case glslang::EOpConstructMat2x3:
1589 case glslang::EOpConstructMat2x4:
1590 case glslang::EOpConstructMat3x2:
1591 case glslang::EOpConstructMat3x3:
1592 case glslang::EOpConstructMat3x4:
1593 case glslang::EOpConstructMat4x2:
1594 case glslang::EOpConstructMat4x3:
1595 case glslang::EOpConstructMat4x4:
1596 case glslang::EOpConstructDMat2x2:
1597 case glslang::EOpConstructDMat2x3:
1598 case glslang::EOpConstructDMat2x4:
1599 case glslang::EOpConstructDMat3x2:
1600 case glslang::EOpConstructDMat3x3:
1601 case glslang::EOpConstructDMat3x4:
1602 case glslang::EOpConstructDMat4x2:
1603 case glslang::EOpConstructDMat4x3:
1604 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001605 case glslang::EOpConstructIMat2x2:
1606 case glslang::EOpConstructIMat2x3:
1607 case glslang::EOpConstructIMat2x4:
1608 case glslang::EOpConstructIMat3x2:
1609 case glslang::EOpConstructIMat3x3:
1610 case glslang::EOpConstructIMat3x4:
1611 case glslang::EOpConstructIMat4x2:
1612 case glslang::EOpConstructIMat4x3:
1613 case glslang::EOpConstructIMat4x4:
1614 case glslang::EOpConstructUMat2x2:
1615 case glslang::EOpConstructUMat2x3:
1616 case glslang::EOpConstructUMat2x4:
1617 case glslang::EOpConstructUMat3x2:
1618 case glslang::EOpConstructUMat3x3:
1619 case glslang::EOpConstructUMat3x4:
1620 case glslang::EOpConstructUMat4x2:
1621 case glslang::EOpConstructUMat4x3:
1622 case glslang::EOpConstructUMat4x4:
1623 case glslang::EOpConstructBMat2x2:
1624 case glslang::EOpConstructBMat2x3:
1625 case glslang::EOpConstructBMat2x4:
1626 case glslang::EOpConstructBMat3x2:
1627 case glslang::EOpConstructBMat3x3:
1628 case glslang::EOpConstructBMat3x4:
1629 case glslang::EOpConstructBMat4x2:
1630 case glslang::EOpConstructBMat4x3:
1631 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001632#ifdef AMD_EXTENSIONS
1633 case glslang::EOpConstructF16Mat2x2:
1634 case glslang::EOpConstructF16Mat2x3:
1635 case glslang::EOpConstructF16Mat2x4:
1636 case glslang::EOpConstructF16Mat3x2:
1637 case glslang::EOpConstructF16Mat3x3:
1638 case glslang::EOpConstructF16Mat3x4:
1639 case glslang::EOpConstructF16Mat4x2:
1640 case glslang::EOpConstructF16Mat4x3:
1641 case glslang::EOpConstructF16Mat4x4:
1642#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001643 isMatrix = true;
1644 // fall through
1645 case glslang::EOpConstructFloat:
1646 case glslang::EOpConstructVec2:
1647 case glslang::EOpConstructVec3:
1648 case glslang::EOpConstructVec4:
1649 case glslang::EOpConstructDouble:
1650 case glslang::EOpConstructDVec2:
1651 case glslang::EOpConstructDVec3:
1652 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001653#ifdef AMD_EXTENSIONS
1654 case glslang::EOpConstructFloat16:
1655 case glslang::EOpConstructF16Vec2:
1656 case glslang::EOpConstructF16Vec3:
1657 case glslang::EOpConstructF16Vec4:
1658#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001659 case glslang::EOpConstructBool:
1660 case glslang::EOpConstructBVec2:
1661 case glslang::EOpConstructBVec3:
1662 case glslang::EOpConstructBVec4:
1663 case glslang::EOpConstructInt:
1664 case glslang::EOpConstructIVec2:
1665 case glslang::EOpConstructIVec3:
1666 case glslang::EOpConstructIVec4:
1667 case glslang::EOpConstructUint:
1668 case glslang::EOpConstructUVec2:
1669 case glslang::EOpConstructUVec3:
1670 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001671 case glslang::EOpConstructInt64:
1672 case glslang::EOpConstructI64Vec2:
1673 case glslang::EOpConstructI64Vec3:
1674 case glslang::EOpConstructI64Vec4:
1675 case glslang::EOpConstructUint64:
1676 case glslang::EOpConstructU64Vec2:
1677 case glslang::EOpConstructU64Vec3:
1678 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001679#ifdef AMD_EXTENSIONS
1680 case glslang::EOpConstructInt16:
1681 case glslang::EOpConstructI16Vec2:
1682 case glslang::EOpConstructI16Vec3:
1683 case glslang::EOpConstructI16Vec4:
1684 case glslang::EOpConstructUint16:
1685 case glslang::EOpConstructU16Vec2:
1686 case glslang::EOpConstructU16Vec3:
1687 case glslang::EOpConstructU16Vec4:
1688#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001689 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001690 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001691 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001692 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001693 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001694 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001695 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001696 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001697 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001698 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001699 std::vector<spv::Id> constituents;
1700 for (int c = 0; c < (int)arguments.size(); ++c)
1701 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001702 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001703 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001704 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001705 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001706 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001707
1708 builder.clearAccessChain();
1709 builder.setAccessChainRValue(constructed);
1710
1711 return false;
1712 }
1713
1714 // These six are component-wise compares with component-wise results.
1715 // Forward on to createBinaryOperation(), requesting a vector result.
1716 case glslang::EOpLessThan:
1717 case glslang::EOpGreaterThan:
1718 case glslang::EOpLessThanEqual:
1719 case glslang::EOpGreaterThanEqual:
1720 case glslang::EOpVectorEqual:
1721 case glslang::EOpVectorNotEqual:
1722 {
1723 // Map the operation to a binary
1724 binOp = node->getOp();
1725 reduceComparison = false;
1726 switch (node->getOp()) {
1727 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1728 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1729 default: binOp = node->getOp(); break;
1730 }
1731
1732 break;
1733 }
1734 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001735 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001736 binOp = glslang::EOpMul;
1737 break;
1738 case glslang::EOpOuterProduct:
1739 // two vectors multiplied to make a matrix
1740 binOp = glslang::EOpOuterProduct;
1741 break;
1742 case glslang::EOpDot:
1743 {
qining25262b32016-05-06 17:25:16 -04001744 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001745 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001746 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001747 binOp = glslang::EOpMul;
1748 break;
1749 }
1750 case glslang::EOpMod:
1751 // when an aggregate, this is the floating-point mod built-in function,
1752 // which can be emitted by the one in createBinaryOperation()
1753 binOp = glslang::EOpMod;
1754 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001755 case glslang::EOpEmitVertex:
1756 case glslang::EOpEndPrimitive:
1757 case glslang::EOpBarrier:
1758 case glslang::EOpMemoryBarrier:
1759 case glslang::EOpMemoryBarrierAtomicCounter:
1760 case glslang::EOpMemoryBarrierBuffer:
1761 case glslang::EOpMemoryBarrierImage:
1762 case glslang::EOpMemoryBarrierShared:
1763 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001764 case glslang::EOpAllMemoryBarrierWithGroupSync:
1765 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1766 case glslang::EOpWorkgroupMemoryBarrier:
1767 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001768 noReturnValue = true;
1769 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1770 break;
1771
John Kessenich426394d2015-07-23 10:22:48 -06001772 case glslang::EOpAtomicAdd:
1773 case glslang::EOpAtomicMin:
1774 case glslang::EOpAtomicMax:
1775 case glslang::EOpAtomicAnd:
1776 case glslang::EOpAtomicOr:
1777 case glslang::EOpAtomicXor:
1778 case glslang::EOpAtomicExchange:
1779 case glslang::EOpAtomicCompSwap:
1780 atomic = true;
1781 break;
1782
John Kessenich0d0c6d32017-07-23 16:08:26 -06001783 case glslang::EOpAtomicCounterAdd:
1784 case glslang::EOpAtomicCounterSubtract:
1785 case glslang::EOpAtomicCounterMin:
1786 case glslang::EOpAtomicCounterMax:
1787 case glslang::EOpAtomicCounterAnd:
1788 case glslang::EOpAtomicCounterOr:
1789 case glslang::EOpAtomicCounterXor:
1790 case glslang::EOpAtomicCounterExchange:
1791 case glslang::EOpAtomicCounterCompSwap:
1792 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1793 builder.addCapability(spv::CapabilityAtomicStorageOps);
1794 atomic = true;
1795 break;
1796
John Kessenich140f3df2015-06-26 16:58:36 -06001797 default:
1798 break;
1799 }
1800
1801 //
1802 // See if it maps to a regular operation.
1803 //
John Kessenich140f3df2015-06-26 16:58:36 -06001804 if (binOp != glslang::EOpNull) {
1805 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1806 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1807 assert(left && right);
1808
1809 builder.clearAccessChain();
1810 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001811 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001812
1813 builder.clearAccessChain();
1814 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001815 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001816
John Kesseniche485c7a2017-05-31 18:50:53 -06001817 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001818 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001819 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001820 left->getType().getBasicType(), reduceComparison);
1821
1822 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001823 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001824 builder.clearAccessChain();
1825 builder.setAccessChainRValue(result);
1826
1827 return false;
1828 }
1829
John Kessenich426394d2015-07-23 10:22:48 -06001830 //
1831 // Create the list of operands.
1832 //
John Kessenich140f3df2015-06-26 16:58:36 -06001833 glslang::TIntermSequence& glslangOperands = node->getSequence();
1834 std::vector<spv::Id> operands;
1835 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001836 // special case l-value operands; there are just a few
1837 bool lvalue = false;
1838 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001839 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001840 case glslang::EOpModf:
1841 if (arg == 1)
1842 lvalue = true;
1843 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001844 case glslang::EOpInterpolateAtSample:
1845 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001846#ifdef AMD_EXTENSIONS
1847 case glslang::EOpInterpolateAtVertex:
1848#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001849 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001850 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001851
1852 // Does it need a swizzle inversion? If so, evaluation is inverted;
1853 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001854 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001855 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1856 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1857 }
Rex Xu7a26c172015-12-08 17:12:09 +08001858 break;
Rex Xud4782c12015-09-06 16:30:11 +08001859 case glslang::EOpAtomicAdd:
1860 case glslang::EOpAtomicMin:
1861 case glslang::EOpAtomicMax:
1862 case glslang::EOpAtomicAnd:
1863 case glslang::EOpAtomicOr:
1864 case glslang::EOpAtomicXor:
1865 case glslang::EOpAtomicExchange:
1866 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001867 case glslang::EOpAtomicCounterAdd:
1868 case glslang::EOpAtomicCounterSubtract:
1869 case glslang::EOpAtomicCounterMin:
1870 case glslang::EOpAtomicCounterMax:
1871 case glslang::EOpAtomicCounterAnd:
1872 case glslang::EOpAtomicCounterOr:
1873 case glslang::EOpAtomicCounterXor:
1874 case glslang::EOpAtomicCounterExchange:
1875 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001876 if (arg == 0)
1877 lvalue = true;
1878 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001879 case glslang::EOpAddCarry:
1880 case glslang::EOpSubBorrow:
1881 if (arg == 2)
1882 lvalue = true;
1883 break;
1884 case glslang::EOpUMulExtended:
1885 case glslang::EOpIMulExtended:
1886 if (arg >= 2)
1887 lvalue = true;
1888 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001889 default:
1890 break;
1891 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001892 builder.clearAccessChain();
1893 if (invertedType != spv::NoType && arg == 0)
1894 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1895 else
1896 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001897 if (lvalue)
1898 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001899 else {
1900 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001901 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001902 }
John Kessenich140f3df2015-06-26 16:58:36 -06001903 }
John Kessenich426394d2015-07-23 10:22:48 -06001904
John Kesseniche485c7a2017-05-31 18:50:53 -06001905 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001906 if (atomic) {
1907 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001908 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001909 } else {
1910 // Pass through to generic operations.
1911 switch (glslangOperands.size()) {
1912 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001913 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001914 break;
1915 case 1:
qining25262b32016-05-06 17:25:16 -04001916 result = createUnaryOperation(
1917 node->getOp(), precision,
1918 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001919 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001920 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001921 break;
1922 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001923 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001924 break;
1925 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001926 if (invertedType)
1927 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001928 }
1929
1930 if (noReturnValue)
1931 return false;
1932
1933 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001934 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001935 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001936 } else {
1937 builder.clearAccessChain();
1938 builder.setAccessChainRValue(result);
1939 return false;
1940 }
1941}
1942
John Kessenich433e9ff2017-01-26 20:31:11 -07001943// This path handles both if-then-else and ?:
1944// The if-then-else has a node type of void, while
1945// ?: has either a void or a non-void node type
1946//
1947// Leaving the result, when not void:
1948// GLSL only has r-values as the result of a :?, but
1949// if we have an l-value, that can be more efficient if it will
1950// become the base of a complex r-value expression, because the
1951// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001952bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1953{
John Kessenich433e9ff2017-01-26 20:31:11 -07001954 // See if it simple and safe to generate OpSelect instead of using control flow.
1955 // Crucially, side effects must be avoided, and there are performance trade-offs.
1956 // Return true if good idea (and safe) for OpSelect, false otherwise.
1957 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001958 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1959 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001960 return false;
1961
1962 if (node->getTrueBlock() == nullptr ||
1963 node->getFalseBlock() == nullptr)
1964 return false;
1965
1966 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1967 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1968
1969 // return true if a single operand to ? : is okay for OpSelect
1970 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001971 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001972 };
1973
1974 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1975 operandOkay(node->getFalseBlock()->getAsTyped());
1976 };
1977
1978 // Emit OpSelect for this selection.
1979 const auto handleAsOpSelect = [&]() {
1980 node->getCondition()->traverse(this);
1981 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1982 node->getTrueBlock()->traverse(this);
1983 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1984 node->getFalseBlock()->traverse(this);
1985 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1986
John Kesseniche485c7a2017-05-31 18:50:53 -06001987 builder.setLine(node->getLoc().line);
1988
John Kesseniche434ad92017-03-30 10:09:28 -06001989 // smear condition to vector, if necessary (AST is always scalar)
1990 if (builder.isVector(trueValue))
1991 condition = builder.smearScalar(spv::NoPrecision, condition,
1992 builder.makeVectorType(builder.makeBoolType(),
1993 builder.getNumComponents(trueValue)));
1994
1995 spv::Id select = builder.createTriOp(spv::OpSelect,
1996 convertGlslangToSpvType(node->getType()), condition,
1997 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001998 builder.clearAccessChain();
1999 builder.setAccessChainRValue(select);
2000 };
2001
2002 // Try for OpSelect
2003
2004 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002005 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2006 if (node->getType().getQualifier().isSpecConstant())
2007 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2008
John Kessenich433e9ff2017-01-26 20:31:11 -07002009 handleAsOpSelect();
2010 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002011 }
2012
Rex Xu57e65922017-07-04 23:23:40 +08002013 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07002014 // Don't handle results as temporaries, because there will be two names
2015 // and better to leave SSA to later passes.
2016 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
2017 ? spv::NoResult
2018 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2019
John Kessenich140f3df2015-06-26 16:58:36 -06002020 // emit the condition before doing anything with selection
2021 node->getCondition()->traverse(this);
2022
Rex Xu57e65922017-07-04 23:23:40 +08002023 // Selection control:
2024 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2025
John Kessenich140f3df2015-06-26 16:58:36 -06002026 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08002027 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06002028
John Kessenich433e9ff2017-01-26 20:31:11 -07002029 // emit the "then" statement
2030 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002031 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002032 if (result != spv::NoResult)
2033 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002034 }
2035
John Kessenich433e9ff2017-01-26 20:31:11 -07002036 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002037 ifBuilder.makeBeginElse();
2038 // emit the "else" statement
2039 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002040 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002041 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002042 }
2043
John Kessenich433e9ff2017-01-26 20:31:11 -07002044 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002045 ifBuilder.makeEndIf();
2046
John Kessenich433e9ff2017-01-26 20:31:11 -07002047 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002048 // GLSL only has r-values as the result of a :?, but
2049 // if we have an l-value, that can be more efficient if it will
2050 // become the base of a complex r-value expression, because the
2051 // next layer copies r-values into memory to use the access-chain mechanism
2052 builder.clearAccessChain();
2053 builder.setAccessChainLValue(result);
2054 }
2055
2056 return false;
2057}
2058
2059bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2060{
2061 // emit and get the condition before doing anything with switch
2062 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002063 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002064
Rex Xu57e65922017-07-04 23:23:40 +08002065 // Selection control:
2066 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2067
John Kessenich140f3df2015-06-26 16:58:36 -06002068 // browse the children to sort out code segments
2069 int defaultSegment = -1;
2070 std::vector<TIntermNode*> codeSegments;
2071 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2072 std::vector<int> caseValues;
2073 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2074 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2075 TIntermNode* child = *c;
2076 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002077 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002078 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002079 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002080 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2081 } else
2082 codeSegments.push_back(child);
2083 }
2084
qining25262b32016-05-06 17:25:16 -04002085 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002086 // statements between the last case and the end of the switch statement
2087 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2088 (int)codeSegments.size() == defaultSegment)
2089 codeSegments.push_back(nullptr);
2090
2091 // make the switch statement
2092 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002093 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002094
2095 // emit all the code in the segments
2096 breakForLoop.push(false);
2097 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2098 builder.nextSwitchSegment(segmentBlocks, s);
2099 if (codeSegments[s])
2100 codeSegments[s]->traverse(this);
2101 else
2102 builder.addSwitchBreak();
2103 }
2104 breakForLoop.pop();
2105
2106 builder.endSwitch(segmentBlocks);
2107
2108 return false;
2109}
2110
2111void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2112{
2113 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002114 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002115
2116 builder.clearAccessChain();
2117 builder.setAccessChainRValue(constant);
2118}
2119
2120bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2121{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002122 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002123 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002124
2125 // Loop control:
2126 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2127
2128 // TODO: dependency length
2129
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002130 // Spec requires back edges to target header blocks, and every header block
2131 // must dominate its merge block. Make a header block first to ensure these
2132 // conditions are met. By definition, it will contain OpLoopMerge, followed
2133 // by a block-ending branch. But we don't want to put any other body/test
2134 // instructions in it, since the body/test may have arbitrary instructions,
2135 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002136 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002137 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002138 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002139 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002140 spv::Block& test = builder.makeNewBlock();
2141 builder.createBranch(&test);
2142
2143 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002144 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002145 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002146 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2147
2148 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002149 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002150 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002151 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002152 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002153 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002154
2155 builder.setBuildPoint(&blocks.continue_target);
2156 if (node->getTerminal())
2157 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002158 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002159 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002160 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002161 builder.createBranch(&blocks.body);
2162
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002163 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002164 builder.setBuildPoint(&blocks.body);
2165 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002166 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002167 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002168 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002169
2170 builder.setBuildPoint(&blocks.continue_target);
2171 if (node->getTerminal())
2172 node->getTerminal()->traverse(this);
2173 if (node->getTest()) {
2174 node->getTest()->traverse(this);
2175 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002176 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002177 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002178 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002179 // TODO: unless there was a break/return/discard instruction
2180 // somewhere in the body, this is an infinite loop, so we should
2181 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002182 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002183 }
John Kessenich140f3df2015-06-26 16:58:36 -06002184 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002185 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002186 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002187 return false;
2188}
2189
2190bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2191{
2192 if (node->getExpression())
2193 node->getExpression()->traverse(this);
2194
John Kesseniche485c7a2017-05-31 18:50:53 -06002195 builder.setLine(node->getLoc().line);
2196
John Kessenich140f3df2015-06-26 16:58:36 -06002197 switch (node->getFlowOp()) {
2198 case glslang::EOpKill:
2199 builder.makeDiscard();
2200 break;
2201 case glslang::EOpBreak:
2202 if (breakForLoop.top())
2203 builder.createLoopExit();
2204 else
2205 builder.addSwitchBreak();
2206 break;
2207 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002208 builder.createLoopContinue();
2209 break;
2210 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002211 if (node->getExpression()) {
2212 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2213 spv::Id returnId = accessChainLoad(glslangReturnType);
2214 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2215 builder.clearAccessChain();
2216 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2217 builder.setAccessChainLValue(copyId);
2218 multiTypeStore(glslangReturnType, returnId);
2219 returnId = builder.createLoad(copyId);
2220 }
2221 builder.makeReturn(false, returnId);
2222 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002223 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002224
2225 builder.clearAccessChain();
2226 break;
2227
2228 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002229 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002230 break;
2231 }
2232
2233 return false;
2234}
2235
2236spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2237{
qining25262b32016-05-06 17:25:16 -04002238 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002239 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002240 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002241 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002242 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002243 }
2244
2245 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002246 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002247 spv::Id spvType = convertGlslangToSpvType(node->getType());
2248
Rex Xuf89ad982017-04-07 23:22:33 +08002249#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002250 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2251 node->getType().containsBasicType(glslang::EbtInt16) ||
2252 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002253 if (contains16BitType) {
2254 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2255 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2256 builder.addCapability(spv::CapabilityStorageInputOutput16);
2257 } else if (storageClass == spv::StorageClassPushConstant) {
2258 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2259 builder.addCapability(spv::CapabilityStoragePushConstant16);
2260 } else if (storageClass == spv::StorageClassUniform) {
2261 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2262 builder.addCapability(spv::CapabilityStorageUniform16);
2263 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2264 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2265 }
2266 }
2267#endif
2268
John Kessenich140f3df2015-06-26 16:58:36 -06002269 const char* name = node->getName().c_str();
2270 if (glslang::IsAnonymous(name))
2271 name = "";
2272
2273 return builder.createVariable(storageClass, spvType, name);
2274}
2275
2276// Return type Id of the sampled type.
2277spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2278{
2279 switch (sampler.type) {
2280 case glslang::EbtFloat: return builder.makeFloatType(32);
2281 case glslang::EbtInt: return builder.makeIntType(32);
2282 case glslang::EbtUint: return builder.makeUintType(32);
2283 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002284 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002285 return builder.makeFloatType(32);
2286 }
2287}
2288
John Kessenich8c8505c2016-07-26 12:50:38 -06002289// If node is a swizzle operation, return the type that should be used if
2290// the swizzle base is first consumed by another operation, before the swizzle
2291// is applied.
2292spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2293{
John Kessenichecba76f2017-01-06 00:34:48 -07002294 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002295 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2296 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2297 else
2298 return spv::NoType;
2299}
2300
2301// When inverting a swizzle with a parent op, this function
2302// will apply the swizzle operation to a completed parent operation.
2303spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2304{
2305 std::vector<unsigned> swizzle;
2306 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2307 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2308}
2309
John Kessenich8c8505c2016-07-26 12:50:38 -06002310// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2311void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2312{
2313 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2314 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2315 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2316}
2317
John Kessenich3ac051e2015-12-20 11:29:16 -07002318// Convert from a glslang type to an SPV type, by calling into a
2319// recursive version of this function. This establishes the inherited
2320// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002321spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2322{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002323 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002324}
2325
2326// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002327// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002328// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002329spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002330{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002331 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002332
2333 switch (type.getBasicType()) {
2334 case glslang::EbtVoid:
2335 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002336 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002337 break;
2338 case glslang::EbtFloat:
2339 spvType = builder.makeFloatType(32);
2340 break;
2341 case glslang::EbtDouble:
2342 spvType = builder.makeFloatType(64);
2343 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002344#ifdef AMD_EXTENSIONS
2345 case glslang::EbtFloat16:
2346 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002347 spvType = builder.makeFloatType(16);
2348 break;
2349#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002350 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002351 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2352 // a 32-bit int where non-0 means true.
2353 if (explicitLayout != glslang::ElpNone)
2354 spvType = builder.makeUintType(32);
2355 else
2356 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002357 break;
2358 case glslang::EbtInt:
2359 spvType = builder.makeIntType(32);
2360 break;
2361 case glslang::EbtUint:
2362 spvType = builder.makeUintType(32);
2363 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002364 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002365 spvType = builder.makeIntType(64);
2366 break;
2367 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002368 spvType = builder.makeUintType(64);
2369 break;
Rex Xucabbb782017-03-24 13:41:14 +08002370#ifdef AMD_EXTENSIONS
2371 case glslang::EbtInt16:
2372 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2373 spvType = builder.makeIntType(16);
2374 break;
2375 case glslang::EbtUint16:
2376 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2377 spvType = builder.makeUintType(16);
2378 break;
2379#endif
John Kessenich426394d2015-07-23 10:22:48 -06002380 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002381 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002382 spvType = builder.makeUintType(32);
2383 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002384 case glslang::EbtSampler:
2385 {
2386 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002387 if (sampler.sampler) {
2388 // pure sampler
2389 spvType = builder.makeSamplerType();
2390 } else {
2391 // an image is present, make its type
2392 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2393 sampler.image ? 2 : 1, TranslateImageFormat(type));
2394 if (sampler.combined) {
2395 // already has both image and sampler, make the combined type
2396 spvType = builder.makeSampledImageType(spvType);
2397 }
John Kessenich55e7d112015-11-15 21:33:39 -07002398 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002399 }
John Kessenich140f3df2015-06-26 16:58:36 -06002400 break;
2401 case glslang::EbtStruct:
2402 case glslang::EbtBlock:
2403 {
2404 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002405 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002406
2407 // Try to share structs for different layouts, but not yet for other
2408 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002409 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002410 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002411 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002412 break;
2413
2414 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002415 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002416 memberRemapper[glslangMembers].resize(glslangMembers->size());
2417 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002418 }
2419 break;
2420 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002421 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002422 break;
2423 }
2424
2425 if (type.isMatrix())
2426 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2427 else {
2428 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2429 if (type.getVectorSize() > 1)
2430 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2431 }
2432
2433 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002434 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2435
John Kessenichc9a80832015-09-12 12:17:44 -06002436 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002437 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002438 // We need to decorate array strides for types needing explicit layout, except blocks.
2439 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002440 // Use a dummy glslang type for querying internal strides of
2441 // arrays of arrays, but using just a one-dimensional array.
2442 glslang::TType simpleArrayType(type, 0); // deference type of the array
2443 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2444 simpleArrayType.getArraySizes().dereference();
2445
2446 // Will compute the higher-order strides here, rather than making a whole
2447 // pile of types and doing repetitive recursion on their contents.
2448 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2449 }
John Kessenichf8842e52016-01-04 19:22:56 -07002450
2451 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002452 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002453 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002454 if (stride > 0)
2455 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002456 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002457 }
2458 } else {
2459 // single-dimensional array, and don't yet have stride
2460
John Kessenichf8842e52016-01-04 19:22:56 -07002461 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002462 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2463 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002464 }
John Kessenich31ed4832015-09-09 17:51:38 -06002465
John Kessenichc9a80832015-09-12 12:17:44 -06002466 // Do the outer dimension, which might not be known for a runtime-sized array
2467 if (type.isRuntimeSizedArray()) {
2468 spvType = builder.makeRuntimeArray(spvType);
2469 } else {
2470 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002471 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002472 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002473 if (stride > 0)
2474 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002475 }
2476
2477 return spvType;
2478}
2479
John Kessenich0e737842017-03-24 18:38:16 -06002480// TODO: this functionality should exist at a higher level, in creating the AST
2481//
2482// Identify interface members that don't have their required extension turned on.
2483//
2484bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2485{
2486 auto& extensions = glslangIntermediate->getRequestedExtensions();
2487
Rex Xubcf291a2017-03-29 23:01:36 +08002488 if (member.getFieldName() == "gl_ViewportMask" &&
2489 extensions.find("GL_NV_viewport_array2") == extensions.end())
2490 return true;
2491 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2492 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2493 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002494 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2495 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2496 return true;
2497 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2498 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2499 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002500 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2501 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2502 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002503
2504 return false;
2505};
2506
John Kessenich6090df02016-06-30 21:18:02 -06002507// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2508// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2509// Mutually recursive with convertGlslangToSpvType().
2510spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2511 const glslang::TTypeList* glslangMembers,
2512 glslang::TLayoutPacking explicitLayout,
2513 const glslang::TQualifier& qualifier)
2514{
2515 // Create a vector of struct types for SPIR-V to consume
2516 std::vector<spv::Id> spvMembers;
2517 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 -06002518 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2519 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2520 if (glslangMember.hiddenMember()) {
2521 ++memberDelta;
2522 if (type.getBasicType() == glslang::EbtBlock)
2523 memberRemapper[glslangMembers][i] = -1;
2524 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002525 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002526 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002527 if (filterMember(glslangMember))
2528 continue;
2529 }
John Kessenich6090df02016-06-30 21:18:02 -06002530 // modify just this child's view of the qualifier
2531 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2532 InheritQualifiers(memberQualifier, qualifier);
2533
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002534 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002535 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002536 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002537
2538 // recurse
2539 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2540 }
2541 }
2542
2543 // Make the SPIR-V type
2544 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002545 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002546 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2547
2548 // Decorate it
2549 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2550
2551 return spvType;
2552}
2553
2554void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2555 const glslang::TTypeList* glslangMembers,
2556 glslang::TLayoutPacking explicitLayout,
2557 const glslang::TQualifier& qualifier,
2558 spv::Id spvType)
2559{
2560 // Name and decorate the non-hidden members
2561 int offset = -1;
2562 int locationOffset = 0; // for use within the members of this struct
2563 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2564 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2565 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002566 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002567 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002568 if (filterMember(glslangMember))
2569 continue;
2570 }
John Kessenich6090df02016-06-30 21:18:02 -06002571
2572 // modify just this child's view of the qualifier
2573 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2574 InheritQualifiers(memberQualifier, qualifier);
2575
2576 // using -1 above to indicate a hidden member
2577 if (member >= 0) {
2578 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2579 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2580 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2581 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002582 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2583 type.getQualifier().storage == glslang::EvqVaryingOut) {
2584 if (type.getBasicType() == glslang::EbtBlock ||
2585 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002586 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2587 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2588 }
2589 }
2590 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2591
Rex Xu286ca432017-07-27 14:33:16 +08002592 if (type.getBasicType() == glslang::EbtBlock &&
2593 qualifier.storage == glslang::EvqBuffer) {
2594 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002595 std::vector<spv::Decoration> memory;
2596 TranslateMemoryDecoration(memberQualifier, memory);
2597 for (unsigned int i = 0; i < memory.size(); ++i)
2598 addMemberDecoration(spvType, member, memory[i]);
2599 }
2600
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002601 // Location assignment was already completed correctly by the front end,
2602 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002603 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002604 // ill-specified and decisions have been made to not allow this.
2605 if (! type.isArray() && memberQualifier.hasLocation())
2606 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002607
John Kessenich2f47bc92016-06-30 21:47:35 -06002608 if (qualifier.hasLocation()) // track for upcoming inheritance
2609 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2610
John Kessenich6090df02016-06-30 21:18:02 -06002611 // component, XFB, others
2612 if (glslangMember.getQualifier().hasComponent())
2613 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2614 if (glslangMember.getQualifier().hasXfbOffset())
2615 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2616 else if (explicitLayout != glslang::ElpNone) {
2617 // figure out what to do with offset, which is accumulating
2618 int nextOffset;
2619 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2620 if (offset >= 0)
2621 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2622 offset = nextOffset;
2623 }
2624
2625 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2626 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2627
2628 // built-in variable decorations
2629 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002630 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002631 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002632
2633#ifdef NV_EXTENSIONS
2634 if (builtIn == spv::BuiltInLayer) {
2635 // SPV_NV_viewport_array2 extension
2636 if (glslangMember.getQualifier().layoutViewportRelative){
2637 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2638 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2639 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2640 }
2641 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2642 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2643 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2644 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2645 }
2646 }
chaocdf3956c2017-02-14 14:52:34 -08002647 if (glslangMember.getQualifier().layoutPassthrough) {
2648 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2649 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2650 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2651 }
chaoc771d89f2017-01-13 01:10:53 -08002652#endif
John Kessenich6090df02016-06-30 21:18:02 -06002653 }
2654 }
2655
2656 // Decorate the structure
2657 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002658 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002659 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2660 builder.addCapability(spv::CapabilityGeometryStreams);
2661 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2662 }
2663 if (glslangIntermediate->getXfbMode()) {
2664 builder.addCapability(spv::CapabilityTransformFeedback);
2665 if (type.getQualifier().hasXfbStride())
2666 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2667 if (type.getQualifier().hasXfbBuffer())
2668 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2669 }
2670}
2671
John Kessenich6c292d32016-02-15 20:58:50 -07002672// Turn the expression forming the array size into an id.
2673// This is not quite trivial, because of specialization constants.
2674// Sometimes, a raw constant is turned into an Id, and sometimes
2675// a specialization constant expression is.
2676spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2677{
2678 // First, see if this is sized with a node, meaning a specialization constant:
2679 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2680 if (specNode != nullptr) {
2681 builder.clearAccessChain();
2682 specNode->traverse(this);
2683 return accessChainLoad(specNode->getAsTyped()->getType());
2684 }
qining25262b32016-05-06 17:25:16 -04002685
John Kessenich6c292d32016-02-15 20:58:50 -07002686 // Otherwise, need a compile-time (front end) size, get it:
2687 int size = arraySizes.getDimSize(dim);
2688 assert(size > 0);
2689 return builder.makeUintConstant(size);
2690}
2691
John Kessenich103bef92016-02-08 21:38:15 -07002692// Wrap the builder's accessChainLoad to:
2693// - localize handling of RelaxedPrecision
2694// - use the SPIR-V inferred type instead of another conversion of the glslang type
2695// (avoids unnecessary work and possible type punning for structures)
2696// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002697spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2698{
John Kessenich103bef92016-02-08 21:38:15 -07002699 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2700 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2701
2702 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002703 if (type.getBasicType() == glslang::EbtBool) {
2704 if (builder.isScalarType(nominalTypeId)) {
2705 // Conversion for bool
2706 spv::Id boolType = builder.makeBoolType();
2707 if (nominalTypeId != boolType)
2708 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2709 } else if (builder.isVectorType(nominalTypeId)) {
2710 // Conversion for bvec
2711 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2712 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2713 if (nominalTypeId != bvecType)
2714 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2715 }
2716 }
John Kessenich103bef92016-02-08 21:38:15 -07002717
2718 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002719}
2720
Rex Xu27253232016-02-23 17:51:09 +08002721// Wrap the builder's accessChainStore to:
2722// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002723//
2724// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002725void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2726{
2727 // Need to convert to abstract types when necessary
2728 if (type.getBasicType() == glslang::EbtBool) {
2729 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2730
2731 if (builder.isScalarType(nominalTypeId)) {
2732 // Conversion for bool
2733 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002734 if (nominalTypeId != boolType) {
2735 // keep these outside arguments, for determinant order-of-evaluation
2736 spv::Id one = builder.makeUintConstant(1);
2737 spv::Id zero = builder.makeUintConstant(0);
2738 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2739 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002740 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002741 } else if (builder.isVectorType(nominalTypeId)) {
2742 // Conversion for bvec
2743 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2744 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002745 if (nominalTypeId != bvecType) {
2746 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002747 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2748 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2749 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002750 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002751 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2752 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002753 }
2754 }
2755
2756 builder.accessChainStore(rvalue);
2757}
2758
John Kessenich4bf71552016-09-02 11:20:21 -06002759// For storing when types match at the glslang level, but not might match at the
2760// SPIR-V level.
2761//
2762// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002763// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002764// as in a member-decorated way.
2765//
2766// NOTE: This function can handle any store request; if it's not special it
2767// simplifies to a simple OpStore.
2768//
2769// Implicitly uses the existing builder.accessChain as the storage target.
2770void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2771{
John Kessenichb3e24e42016-09-11 12:33:43 -06002772 // we only do the complex path here if it's an aggregate
2773 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002774 accessChainStore(type, rValue);
2775 return;
2776 }
2777
John Kessenichb3e24e42016-09-11 12:33:43 -06002778 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002779 spv::Id rType = builder.getTypeId(rValue);
2780 spv::Id lValue = builder.accessChainGetLValue();
2781 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2782 if (lType == rType) {
2783 accessChainStore(type, rValue);
2784 return;
2785 }
2786
John Kessenichb3e24e42016-09-11 12:33:43 -06002787 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002788 // where the two types were the same type in GLSL. This requires member
2789 // by member copy, recursively.
2790
John Kessenichb3e24e42016-09-11 12:33:43 -06002791 // If an array, copy element by element.
2792 if (type.isArray()) {
2793 glslang::TType glslangElementType(type, 0);
2794 spv::Id elementRType = builder.getContainedTypeId(rType);
2795 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2796 // get the source member
2797 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002798
John Kessenichb3e24e42016-09-11 12:33:43 -06002799 // set up the target storage
2800 builder.clearAccessChain();
2801 builder.setAccessChainLValue(lValue);
2802 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002803
John Kessenichb3e24e42016-09-11 12:33:43 -06002804 // store the member
2805 multiTypeStore(glslangElementType, elementRValue);
2806 }
2807 } else {
2808 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002809
John Kessenichb3e24e42016-09-11 12:33:43 -06002810 // loop over structure members
2811 const glslang::TTypeList& members = *type.getStruct();
2812 for (int m = 0; m < (int)members.size(); ++m) {
2813 const glslang::TType& glslangMemberType = *members[m].type;
2814
2815 // get the source member
2816 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2817 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2818
2819 // set up the target storage
2820 builder.clearAccessChain();
2821 builder.setAccessChainLValue(lValue);
2822 builder.accessChainPush(builder.makeIntConstant(m));
2823
2824 // store the member
2825 multiTypeStore(glslangMemberType, memberRValue);
2826 }
John Kessenich4bf71552016-09-02 11:20:21 -06002827 }
2828}
2829
John Kessenichf85e8062015-12-19 13:57:10 -07002830// Decide whether or not this type should be
2831// decorated with offsets and strides, and if so
2832// whether std140 or std430 rules should be applied.
2833glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002834{
John Kessenichf85e8062015-12-19 13:57:10 -07002835 // has to be a block
2836 if (type.getBasicType() != glslang::EbtBlock)
2837 return glslang::ElpNone;
2838
2839 // has to be a uniform or buffer block
2840 if (type.getQualifier().storage != glslang::EvqUniform &&
2841 type.getQualifier().storage != glslang::EvqBuffer)
2842 return glslang::ElpNone;
2843
2844 // return the layout to use
2845 switch (type.getQualifier().layoutPacking) {
2846 case glslang::ElpStd140:
2847 case glslang::ElpStd430:
2848 return type.getQualifier().layoutPacking;
2849 default:
2850 return glslang::ElpNone;
2851 }
John Kessenich31ed4832015-09-09 17:51:38 -06002852}
2853
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002854// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002855int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002856{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002857 int size;
John Kessenich49987892015-12-29 17:11:44 -07002858 int stride;
2859 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002860
2861 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002862}
2863
John Kessenich49987892015-12-29 17:11:44 -07002864// 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 -07002865// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002866int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002867{
John Kessenich49987892015-12-29 17:11:44 -07002868 glslang::TType elementType;
2869 elementType.shallowCopy(matrixType);
2870 elementType.clearArraySizes();
2871
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002872 int size;
John Kessenich49987892015-12-29 17:11:44 -07002873 int stride;
2874 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2875
2876 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002877}
2878
John Kessenich5e4b1242015-08-06 22:53:06 -06002879// Given a member type of a struct, realign the current offset for it, and compute
2880// the next (not yet aligned) offset for the next member, which will get aligned
2881// on the next call.
2882// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2883// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2884// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002885void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002886 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002887{
2888 // this will get a positive value when deemed necessary
2889 nextOffset = -1;
2890
John Kessenich5e4b1242015-08-06 22:53:06 -06002891 // override anything in currentOffset with user-set offset
2892 if (memberType.getQualifier().hasOffset())
2893 currentOffset = memberType.getQualifier().layoutOffset;
2894
2895 // It could be that current linker usage in glslang updated all the layoutOffset,
2896 // in which case the following code does not matter. But, that's not quite right
2897 // once cross-compilation unit GLSL validation is done, as the original user
2898 // settings are needed in layoutOffset, and then the following will come into play.
2899
John Kessenichf85e8062015-12-19 13:57:10 -07002900 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002901 if (! memberType.getQualifier().hasOffset())
2902 currentOffset = -1;
2903
2904 return;
2905 }
2906
John Kessenichf85e8062015-12-19 13:57:10 -07002907 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002908 if (currentOffset < 0)
2909 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002910
John Kessenich5e4b1242015-08-06 22:53:06 -06002911 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2912 // but possibly not yet correctly aligned.
2913
2914 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002915 int dummyStride;
2916 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002917
2918 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002919 // TODO: make this consistent in early phases of code:
2920 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2921 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2922 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002923 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002924 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002925 int dummySize;
2926 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2927 if (componentAlignment <= 4)
2928 memberAlignment = componentAlignment;
2929 }
2930
2931 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002932 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002933
2934 // Bump up to vec4 if there is a bad straddle
2935 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2936 glslang::RoundToPow2(currentOffset, 16);
2937
John Kessenich5e4b1242015-08-06 22:53:06 -06002938 nextOffset = currentOffset + memberSize;
2939}
2940
David Netoa901ffe2016-06-08 14:11:40 +01002941void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002942{
David Netoa901ffe2016-06-08 14:11:40 +01002943 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2944 switch (glslangBuiltIn)
2945 {
2946 case glslang::EbvClipDistance:
2947 case glslang::EbvCullDistance:
2948 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002949#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08002950 case glslang::EbvViewportMaskNV:
2951 case glslang::EbvSecondaryPositionNV:
2952 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002953 case glslang::EbvPositionPerViewNV:
2954 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002955#endif
David Netoa901ffe2016-06-08 14:11:40 +01002956 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2957 // Alternately, we could just call this for any glslang built-in, since the
2958 // capability already guards against duplicates.
2959 TranslateBuiltInDecoration(glslangBuiltIn, false);
2960 break;
2961 default:
2962 // Capabilities were already generated when the struct was declared.
2963 break;
2964 }
John Kessenichebb50532016-05-16 19:22:05 -06002965}
2966
John Kessenich6fccb3c2016-09-19 16:01:41 -06002967bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002968{
John Kessenicheee9d532016-09-19 18:09:30 -06002969 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002970}
2971
2972// Make all the functions, skeletally, without actually visiting their bodies.
2973void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2974{
John Kessenichfad62972017-07-18 02:35:46 -06002975 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
2976 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
2977 if (paramPrecision != spv::NoPrecision)
2978 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06002979 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06002980 };
2981
John Kessenich140f3df2015-06-26 16:58:36 -06002982 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2983 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002984 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002985 continue;
2986
2987 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002988 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002989 //
qining25262b32016-05-06 17:25:16 -04002990 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002991 // function. What it is an address of varies:
2992 //
John Kessenich4bf71552016-09-02 11:20:21 -06002993 // - "in" parameters not marked as "const" can be written to without modifying the calling
2994 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002995 //
2996 // - "const in" parameters can just be the r-value, as no writes need occur.
2997 //
John Kessenich4bf71552016-09-02 11:20:21 -06002998 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2999 // 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 -06003000
3001 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003002 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003003 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3004
John Kessenichfad62972017-07-18 02:35:46 -06003005 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3006 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003007
John Kessenichbed4e4f2017-09-08 02:38:07 -06003008 const auto canPassOriginal = [&](const glslang::TType& paramType, bool firstParam) -> bool {
3009 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
3010 return firstParam && implicitThis;
3011 else
3012 return paramType.containsOpaque() || // sampler, etc.
3013 (paramType.getBasicType() == glslang::EbtBlock &&
3014 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
3015 (firstParam && implicitThis); // implicit 'this'
3016 };
3017
John Kessenichfad62972017-07-18 02:35:46 -06003018 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003019 for (int p = 0; p < (int)parameters.size(); ++p) {
3020 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3021 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichbed4e4f2017-09-08 02:38:07 -06003022 if (canPassOriginal(paramType, p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003023 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07003024 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003025 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3026 else
John Kessenich4bf71552016-09-02 11:20:21 -06003027 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003028 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003029 paramTypes.push_back(typeId);
3030 }
3031
3032 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003033 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3034 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003035 glslFunction->getName().c_str(), paramTypes,
3036 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003037 if (implicitThis)
3038 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003039
3040 // Track function to emit/call later
3041 functionMap[glslFunction->getName().c_str()] = function;
3042
3043 // Set the parameter id's
3044 for (int p = 0; p < (int)parameters.size(); ++p) {
3045 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3046 // give a name too
3047 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3048 }
3049 }
3050}
3051
3052// Process all the initializers, while skipping the functions and link objects
3053void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3054{
3055 builder.setBuildPoint(shaderEntry->getLastBlock());
3056 for (int i = 0; i < (int)initializers.size(); ++i) {
3057 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3058 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3059
3060 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003061 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003062 initializer->traverse(this);
3063 }
3064 }
3065}
3066
3067// Process all the functions, while skipping initializers.
3068void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3069{
3070 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3071 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003072 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003073 node->traverse(this);
3074 }
3075}
3076
3077void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3078{
qining25262b32016-05-06 17:25:16 -04003079 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003080 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003081 currentFunction = functionMap[node->getName().c_str()];
3082 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003083 builder.setBuildPoint(functionBlock);
3084}
3085
Rex Xu04db3f52015-09-16 11:44:02 +08003086void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003087{
Rex Xufc618912015-09-09 16:42:49 +08003088 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003089
3090 glslang::TSampler sampler = {};
3091 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003092 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003093 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3094 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3095 }
3096
John Kessenich140f3df2015-06-26 16:58:36 -06003097 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3098 builder.clearAccessChain();
3099 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003100
3101 // Special case l-value operands
3102 bool lvalue = false;
3103 switch (node.getOp()) {
3104 case glslang::EOpImageAtomicAdd:
3105 case glslang::EOpImageAtomicMin:
3106 case glslang::EOpImageAtomicMax:
3107 case glslang::EOpImageAtomicAnd:
3108 case glslang::EOpImageAtomicOr:
3109 case glslang::EOpImageAtomicXor:
3110 case glslang::EOpImageAtomicExchange:
3111 case glslang::EOpImageAtomicCompSwap:
3112 if (i == 0)
3113 lvalue = true;
3114 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003115 case glslang::EOpSparseImageLoad:
3116 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3117 lvalue = true;
3118 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003119 case glslang::EOpSparseTexture:
3120 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3121 lvalue = true;
3122 break;
3123 case glslang::EOpSparseTextureClamp:
3124 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3125 lvalue = true;
3126 break;
3127 case glslang::EOpSparseTextureLod:
3128 case glslang::EOpSparseTextureOffset:
3129 if (i == 3)
3130 lvalue = true;
3131 break;
3132 case glslang::EOpSparseTextureFetch:
3133 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3134 lvalue = true;
3135 break;
3136 case glslang::EOpSparseTextureFetchOffset:
3137 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3138 lvalue = true;
3139 break;
3140 case glslang::EOpSparseTextureLodOffset:
3141 case glslang::EOpSparseTextureGrad:
3142 case glslang::EOpSparseTextureOffsetClamp:
3143 if (i == 4)
3144 lvalue = true;
3145 break;
3146 case glslang::EOpSparseTextureGradOffset:
3147 case glslang::EOpSparseTextureGradClamp:
3148 if (i == 5)
3149 lvalue = true;
3150 break;
3151 case glslang::EOpSparseTextureGradOffsetClamp:
3152 if (i == 6)
3153 lvalue = true;
3154 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003155 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003156 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3157 lvalue = true;
3158 break;
3159 case glslang::EOpSparseTextureGatherOffset:
3160 case glslang::EOpSparseTextureGatherOffsets:
3161 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3162 lvalue = true;
3163 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003164#ifdef AMD_EXTENSIONS
3165 case glslang::EOpSparseTextureGatherLod:
3166 if (i == 3)
3167 lvalue = true;
3168 break;
3169 case glslang::EOpSparseTextureGatherLodOffset:
3170 case glslang::EOpSparseTextureGatherLodOffsets:
3171 if (i == 4)
3172 lvalue = true;
3173 break;
Rex Xu129799a2017-07-05 17:23:28 +08003174 case glslang::EOpSparseImageLoadLod:
3175 if (i == 3)
3176 lvalue = true;
3177 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003178#endif
Rex Xufc618912015-09-09 16:42:49 +08003179 default:
3180 break;
3181 }
3182
Rex Xu6b86d492015-09-16 17:48:22 +08003183 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003184 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003185 else
John Kessenich32cfd492016-02-02 12:37:46 -07003186 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003187 }
3188}
3189
John Kessenichfc51d282015-08-19 13:34:18 -06003190void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003191{
John Kessenichfc51d282015-08-19 13:34:18 -06003192 builder.clearAccessChain();
3193 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003194 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003195}
John Kessenich140f3df2015-06-26 16:58:36 -06003196
John Kessenichfc51d282015-08-19 13:34:18 -06003197spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3198{
John Kesseniche485c7a2017-05-31 18:50:53 -06003199 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003200 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003201
3202 builder.setLine(node->getLoc().line);
3203
John Kessenich8c8505c2016-07-26 12:50:38 -06003204 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003205
John Kessenichfc51d282015-08-19 13:34:18 -06003206 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003207 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3208 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3209 std::vector<spv::Id> arguments;
3210 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003211 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003212 else
3213 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003214 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003215
3216 spv::Builder::TextureParameters params = { };
3217 params.sampler = arguments[0];
3218
Rex Xu04db3f52015-09-16 11:44:02 +08003219 glslang::TCrackedTextureOp cracked;
3220 node->crackTexture(sampler, cracked);
3221
amhagan05506bb2017-06-13 16:53:02 -04003222 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003223
John Kessenichfc51d282015-08-19 13:34:18 -06003224 // Check for queries
3225 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003226 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3227 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003228 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003229
John Kessenichfc51d282015-08-19 13:34:18 -06003230 switch (node->getOp()) {
3231 case glslang::EOpImageQuerySize:
3232 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003233 if (arguments.size() > 1) {
3234 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003235 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003236 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003237 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003238 case glslang::EOpImageQuerySamples:
3239 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003240 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003241 case glslang::EOpTextureQueryLod:
3242 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003243 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003244 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003245 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003246 case glslang::EOpSparseTexelsResident:
3247 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003248 default:
3249 assert(0);
3250 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003251 }
John Kessenich140f3df2015-06-26 16:58:36 -06003252 }
3253
Rex Xufc618912015-09-09 16:42:49 +08003254 // Check for image functions other than queries
3255 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003256 std::vector<spv::Id> operands;
3257 auto opIt = arguments.begin();
3258 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003259
3260 // Handle subpass operations
3261 // TODO: GLSL should change to have the "MS" only on the type rather than the
3262 // built-in function.
3263 if (cracked.subpass) {
3264 // add on the (0,0) coordinate
3265 spv::Id zero = builder.makeIntConstant(0);
3266 std::vector<spv::Id> comps;
3267 comps.push_back(zero);
3268 comps.push_back(zero);
3269 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3270 if (sampler.ms) {
3271 operands.push_back(spv::ImageOperandsSampleMask);
3272 operands.push_back(*(opIt++));
3273 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003274 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003275 }
3276
John Kessenich56bab042015-09-16 10:54:31 -06003277 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003278#ifdef AMD_EXTENSIONS
3279 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3280#else
John Kessenich56bab042015-09-16 10:54:31 -06003281 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003282#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003283 if (sampler.ms) {
3284 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003285 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003286#ifdef AMD_EXTENSIONS
3287 } else if (cracked.lod) {
3288 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3289 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3290
3291 operands.push_back(spv::ImageOperandsLodMask);
3292 operands.push_back(*opIt);
3293#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003294 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003295 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3296 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003297 return builder.createOp(spv::OpImageRead, resultType(), operands);
Rex Xu129799a2017-07-05 17:23:28 +08003298#ifdef AMD_EXTENSIONS
3299 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3300#else
John Kessenich56bab042015-09-16 10:54:31 -06003301 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003302#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003303 if (sampler.ms) {
3304 operands.push_back(*(opIt + 1));
3305 operands.push_back(spv::ImageOperandsSampleMask);
3306 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003307#ifdef AMD_EXTENSIONS
3308 } else if (cracked.lod) {
3309 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3310 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3311
3312 operands.push_back(*(opIt + 1));
3313 operands.push_back(spv::ImageOperandsLodMask);
3314 operands.push_back(*opIt);
3315#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003316 } else
3317 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003318 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003319 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3320 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003321 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003322#ifdef AMD_EXTENSIONS
3323 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3324#else
Rex Xu5eafa472016-02-19 22:24:03 +08003325 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003326#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003327 builder.addCapability(spv::CapabilitySparseResidency);
3328 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3329 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3330
3331 if (sampler.ms) {
3332 operands.push_back(spv::ImageOperandsSampleMask);
3333 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003334#ifdef AMD_EXTENSIONS
3335 } else if (cracked.lod) {
3336 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3337 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3338
3339 operands.push_back(spv::ImageOperandsLodMask);
3340 operands.push_back(*opIt++);
3341#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003342 }
3343
3344 // Create the return type that was a special structure
3345 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003346 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003347 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3348 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3349
3350 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3351
3352 // Decode the return type
3353 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3354 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003355 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003356 // Process image atomic operations
3357
3358 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3359 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003360 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003361
John Kessenich8c8505c2016-07-26 12:50:38 -06003362 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003363 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003364
3365 std::vector<spv::Id> operands;
3366 operands.push_back(pointer);
3367 for (; opIt != arguments.end(); ++opIt)
3368 operands.push_back(*opIt);
3369
John Kessenich8c8505c2016-07-26 12:50:38 -06003370 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003371 }
3372 }
3373
amhagan05506bb2017-06-13 16:53:02 -04003374#ifdef AMD_EXTENSIONS
3375 // Check for fragment mask functions other than queries
3376 if (cracked.fragMask) {
3377 assert(sampler.ms);
3378
3379 auto opIt = arguments.begin();
3380 std::vector<spv::Id> operands;
3381
3382 // Extract the image if necessary
3383 if (builder.isSampledImage(params.sampler))
3384 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3385
3386 operands.push_back(params.sampler);
3387 ++opIt;
3388
3389 if (sampler.isSubpass()) {
3390 // add on the (0,0) coordinate
3391 spv::Id zero = builder.makeIntConstant(0);
3392 std::vector<spv::Id> comps;
3393 comps.push_back(zero);
3394 comps.push_back(zero);
3395 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3396 }
3397
3398 for (; opIt != arguments.end(); ++opIt)
3399 operands.push_back(*opIt);
3400
3401 spv::Op fragMaskOp = spv::OpNop;
3402 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3403 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3404 else if (node->getOp() == glslang::EOpFragmentFetch)
3405 fragMaskOp = spv::OpFragmentFetchAMD;
3406
3407 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3408 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3409 return builder.createOp(fragMaskOp, resultType(), operands);
3410 }
3411#endif
3412
Rex Xufc618912015-09-09 16:42:49 +08003413 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003414 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003415 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3416
John Kessenichfc51d282015-08-19 13:34:18 -06003417 // check for bias argument
3418 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003419#ifdef AMD_EXTENSIONS
3420 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3421#else
Rex Xu71519fe2015-11-11 15:35:47 +08003422 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003423#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003424 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003425#ifdef AMD_EXTENSIONS
3426 if (cracked.gather)
3427 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3428#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003429 if (cracked.offset)
3430 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003431#ifdef AMD_EXTENSIONS
3432 else if (cracked.offsets)
3433 ++nonBiasArgCount;
3434#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003435 if (cracked.grad)
3436 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003437 if (cracked.lodClamp)
3438 ++nonBiasArgCount;
3439 if (sparse)
3440 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003441
3442 if ((int)arguments.size() > nonBiasArgCount)
3443 bias = true;
3444 }
3445
John Kessenicha5c33d62016-06-02 23:45:21 -06003446 // See if the sampler param should really be just the SPV image part
3447 if (cracked.fetch) {
3448 // a fetch needs to have the image extracted first
3449 if (builder.isSampledImage(params.sampler))
3450 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3451 }
3452
Rex Xu225e0fc2016-11-17 17:47:59 +08003453#ifdef AMD_EXTENSIONS
3454 if (cracked.gather) {
3455 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3456 if (bias || cracked.lod ||
3457 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3458 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003459 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003460 }
3461 }
3462#endif
3463
John Kessenichfc51d282015-08-19 13:34:18 -06003464 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003465
John Kessenichfc51d282015-08-19 13:34:18 -06003466 params.coords = arguments[1];
3467 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003468 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003469
3470 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003471 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003472 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003473 ++extraArgs;
3474 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003475 params.Dref = arguments[2];
3476 ++extraArgs;
3477 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003478 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003479 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003480 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003481 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003482 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003483 dRefComp = builder.getNumComponents(params.coords) - 1;
3484 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003485 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3486 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003487
3488 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003489 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003490 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003491 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003492 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3493 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3494 noImplicitLod = true;
3495 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003496
3497 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003498 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003499 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003500 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003501 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003502
3503 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003504 if (cracked.grad) {
3505 params.gradX = arguments[2 + extraArgs];
3506 params.gradY = arguments[3 + extraArgs];
3507 extraArgs += 2;
3508 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003509
3510 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003511 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003512 params.offset = arguments[2 + extraArgs];
3513 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003514 } else if (cracked.offsets) {
3515 params.offsets = arguments[2 + extraArgs];
3516 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003517 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003518
3519 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003520 if (cracked.lodClamp) {
3521 params.lodClamp = arguments[2 + extraArgs];
3522 ++extraArgs;
3523 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003524
3525 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003526 if (sparse) {
3527 params.texelOut = arguments[2 + extraArgs];
3528 ++extraArgs;
3529 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003530
John Kessenich76d4dfc2016-06-16 12:43:23 -06003531 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003532 if (cracked.gather && ! sampler.shadow) {
3533 // default component is 0, if missing, otherwise an argument
3534 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003535 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003536 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003537 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003538 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003539 }
3540
3541 // bias
3542 if (bias) {
3543 params.bias = arguments[2 + extraArgs];
3544 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003545 }
John Kessenichfc51d282015-08-19 13:34:18 -06003546
John Kessenich65336482016-06-16 14:06:26 -06003547 // projective component (might not to move)
3548 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3549 // are divided by the last component of P."
3550 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3551 // unused components will appear after all used components."
3552 if (cracked.proj) {
3553 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3554 int projTargetComp;
3555 switch (sampler.dim) {
3556 case glslang::Esd1D: projTargetComp = 1; break;
3557 case glslang::Esd2D: projTargetComp = 2; break;
3558 case glslang::EsdRect: projTargetComp = 2; break;
3559 default: projTargetComp = projSourceComp; break;
3560 }
3561 // copy the projective coordinate if we have to
3562 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003563 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003564 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3565 projSourceComp);
3566 params.coords = builder.createCompositeInsert(projComp, params.coords,
3567 builder.getTypeId(params.coords), projTargetComp);
3568 }
3569 }
3570
John Kessenich8c8505c2016-07-26 12:50:38 -06003571 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003572}
3573
3574spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3575{
3576 // Grab the function's pointer from the previously created function
3577 spv::Function* function = functionMap[node->getName().c_str()];
3578 if (! function)
3579 return 0;
3580
3581 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3582 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3583
John Kessenichbed4e4f2017-09-08 02:38:07 -06003584 // Encapsulate lvalue logic, used in multiple places below, for safety.
3585 const auto isLValue = [&](int qualifier, const glslang::TType& paramType) -> bool {
3586 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
3587 return qualifier != glslang::EvqConstReadOnly;
LoopDawg76117922017-09-06 14:59:06 -06003588 return qualifier != glslang::EvqConstReadOnly || paramType.containsOpaque();
3589 };
3590
John Kessenich140f3df2015-06-26 16:58:36 -06003591 // See comments in makeFunctions() for details about the semantics for parameter passing.
3592 //
3593 // These imply we need a four step process:
3594 // 1. Evaluate the arguments
3595 // 2. Allocate and make copies of in, out, and inout arguments
3596 // 3. Make the call
3597 // 4. Copy back the results
3598
3599 // 1. Evaluate the arguments
3600 std::vector<spv::Builder::AccessChain> lValues;
3601 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003602 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003603 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003604 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003605 // build l-value
3606 builder.clearAccessChain();
3607 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003608 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003609 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
LoopDawg76117922017-09-06 14:59:06 -06003610 if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003611 // save l-value
3612 lValues.push_back(builder.getAccessChain());
3613 } else {
3614 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003615 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003616 }
3617 }
3618
3619 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3620 // copy the original into that space.
3621 //
3622 // Also, build up the list of actual arguments to pass in for the call
3623 int lValueCount = 0;
3624 int rValueCount = 0;
3625 std::vector<spv::Id> spvArgs;
3626 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003627 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003628 spv::Id arg;
John Kessenichbed4e4f2017-09-08 02:38:07 -06003629 if ((a == 0 && function->hasImplicitThis()) ||
3630 (glslangIntermediate->getSource() != glslang::EShSourceHlsl &&
3631 (paramType.containsOpaque() ||
3632 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer)))) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003633 builder.setAccessChain(lValues[lValueCount]);
3634 arg = builder.accessChainGetLValue();
3635 ++lValueCount;
LoopDawg76117922017-09-06 14:59:06 -06003636 } else if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003637 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003638 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3639 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3640 // need to copy the input into output space
3641 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003642 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003643 builder.clearAccessChain();
3644 builder.setAccessChainLValue(arg);
3645 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003646 }
3647 ++lValueCount;
3648 } else {
3649 arg = rValues[rValueCount];
3650 ++rValueCount;
3651 }
3652 spvArgs.push_back(arg);
3653 }
3654
3655 // 3. Make the call.
3656 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003657 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003658
3659 // 4. Copy back out an "out" arguments.
3660 lValueCount = 0;
3661 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003662 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
LoopDawg76117922017-09-06 14:59:06 -06003663 if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003664 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3665 spv::Id copy = builder.createLoad(spvArgs[a]);
3666 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003667 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003668 }
3669 ++lValueCount;
3670 }
3671 }
3672
3673 return result;
3674}
3675
3676// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003677spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3678 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003679 spv::Id typeId, spv::Id left, spv::Id right,
3680 glslang::TBasicType typeProxy, bool reduceComparison)
3681{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003682#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003683 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003684 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3685#else
Rex Xucabbb782017-03-24 13:41:14 +08003686 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003687 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003688#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003689 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003690
3691 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003692 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003693 bool comparison = false;
3694
3695 switch (op) {
3696 case glslang::EOpAdd:
3697 case glslang::EOpAddAssign:
3698 if (isFloat)
3699 binOp = spv::OpFAdd;
3700 else
3701 binOp = spv::OpIAdd;
3702 break;
3703 case glslang::EOpSub:
3704 case glslang::EOpSubAssign:
3705 if (isFloat)
3706 binOp = spv::OpFSub;
3707 else
3708 binOp = spv::OpISub;
3709 break;
3710 case glslang::EOpMul:
3711 case glslang::EOpMulAssign:
3712 if (isFloat)
3713 binOp = spv::OpFMul;
3714 else
3715 binOp = spv::OpIMul;
3716 break;
3717 case glslang::EOpVectorTimesScalar:
3718 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003719 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003720 if (builder.isVector(right))
3721 std::swap(left, right);
3722 assert(builder.isScalar(right));
3723 needMatchingVectors = false;
3724 binOp = spv::OpVectorTimesScalar;
3725 } else
3726 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003727 break;
3728 case glslang::EOpVectorTimesMatrix:
3729 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003730 binOp = spv::OpVectorTimesMatrix;
3731 break;
3732 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003733 binOp = spv::OpMatrixTimesVector;
3734 break;
3735 case glslang::EOpMatrixTimesScalar:
3736 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003737 binOp = spv::OpMatrixTimesScalar;
3738 break;
3739 case glslang::EOpMatrixTimesMatrix:
3740 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003741 binOp = spv::OpMatrixTimesMatrix;
3742 break;
3743 case glslang::EOpOuterProduct:
3744 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003745 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003746 break;
3747
3748 case glslang::EOpDiv:
3749 case glslang::EOpDivAssign:
3750 if (isFloat)
3751 binOp = spv::OpFDiv;
3752 else if (isUnsigned)
3753 binOp = spv::OpUDiv;
3754 else
3755 binOp = spv::OpSDiv;
3756 break;
3757 case glslang::EOpMod:
3758 case glslang::EOpModAssign:
3759 if (isFloat)
3760 binOp = spv::OpFMod;
3761 else if (isUnsigned)
3762 binOp = spv::OpUMod;
3763 else
3764 binOp = spv::OpSMod;
3765 break;
3766 case glslang::EOpRightShift:
3767 case glslang::EOpRightShiftAssign:
3768 if (isUnsigned)
3769 binOp = spv::OpShiftRightLogical;
3770 else
3771 binOp = spv::OpShiftRightArithmetic;
3772 break;
3773 case glslang::EOpLeftShift:
3774 case glslang::EOpLeftShiftAssign:
3775 binOp = spv::OpShiftLeftLogical;
3776 break;
3777 case glslang::EOpAnd:
3778 case glslang::EOpAndAssign:
3779 binOp = spv::OpBitwiseAnd;
3780 break;
3781 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003782 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003783 binOp = spv::OpLogicalAnd;
3784 break;
3785 case glslang::EOpInclusiveOr:
3786 case glslang::EOpInclusiveOrAssign:
3787 binOp = spv::OpBitwiseOr;
3788 break;
3789 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003790 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003791 binOp = spv::OpLogicalOr;
3792 break;
3793 case glslang::EOpExclusiveOr:
3794 case glslang::EOpExclusiveOrAssign:
3795 binOp = spv::OpBitwiseXor;
3796 break;
3797 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003798 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003799 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003800 break;
3801
3802 case glslang::EOpLessThan:
3803 case glslang::EOpGreaterThan:
3804 case glslang::EOpLessThanEqual:
3805 case glslang::EOpGreaterThanEqual:
3806 case glslang::EOpEqual:
3807 case glslang::EOpNotEqual:
3808 case glslang::EOpVectorEqual:
3809 case glslang::EOpVectorNotEqual:
3810 comparison = true;
3811 break;
3812 default:
3813 break;
3814 }
3815
John Kessenich7c1aa102015-10-15 13:29:11 -06003816 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003817 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003818 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003819 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003820 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003821
3822 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003823 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003824 builder.promoteScalar(precision, left, right);
3825
qining25262b32016-05-06 17:25:16 -04003826 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3827 addDecoration(result, noContraction);
3828 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003829 }
3830
3831 if (! comparison)
3832 return 0;
3833
John Kessenich7c1aa102015-10-15 13:29:11 -06003834 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003835
John Kessenich4583b612016-08-07 19:14:22 -06003836 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3837 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003838 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003839
3840 switch (op) {
3841 case glslang::EOpLessThan:
3842 if (isFloat)
3843 binOp = spv::OpFOrdLessThan;
3844 else if (isUnsigned)
3845 binOp = spv::OpULessThan;
3846 else
3847 binOp = spv::OpSLessThan;
3848 break;
3849 case glslang::EOpGreaterThan:
3850 if (isFloat)
3851 binOp = spv::OpFOrdGreaterThan;
3852 else if (isUnsigned)
3853 binOp = spv::OpUGreaterThan;
3854 else
3855 binOp = spv::OpSGreaterThan;
3856 break;
3857 case glslang::EOpLessThanEqual:
3858 if (isFloat)
3859 binOp = spv::OpFOrdLessThanEqual;
3860 else if (isUnsigned)
3861 binOp = spv::OpULessThanEqual;
3862 else
3863 binOp = spv::OpSLessThanEqual;
3864 break;
3865 case glslang::EOpGreaterThanEqual:
3866 if (isFloat)
3867 binOp = spv::OpFOrdGreaterThanEqual;
3868 else if (isUnsigned)
3869 binOp = spv::OpUGreaterThanEqual;
3870 else
3871 binOp = spv::OpSGreaterThanEqual;
3872 break;
3873 case glslang::EOpEqual:
3874 case glslang::EOpVectorEqual:
3875 if (isFloat)
3876 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003877 else if (isBool)
3878 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003879 else
3880 binOp = spv::OpIEqual;
3881 break;
3882 case glslang::EOpNotEqual:
3883 case glslang::EOpVectorNotEqual:
3884 if (isFloat)
3885 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003886 else if (isBool)
3887 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003888 else
3889 binOp = spv::OpINotEqual;
3890 break;
3891 default:
3892 break;
3893 }
3894
qining25262b32016-05-06 17:25:16 -04003895 if (binOp != spv::OpNop) {
3896 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3897 addDecoration(result, noContraction);
3898 return builder.setPrecision(result, precision);
3899 }
John Kessenich140f3df2015-06-26 16:58:36 -06003900
3901 return 0;
3902}
3903
John Kessenich04bb8a02015-12-12 12:28:14 -07003904//
3905// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3906// These can be any of:
3907//
3908// matrix * scalar
3909// scalar * matrix
3910// matrix * matrix linear algebraic
3911// matrix * vector
3912// vector * matrix
3913// matrix * matrix componentwise
3914// matrix op matrix op in {+, -, /}
3915// matrix op scalar op in {+, -, /}
3916// scalar op matrix op in {+, -, /}
3917//
qining25262b32016-05-06 17:25:16 -04003918spv::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 -07003919{
3920 bool firstClass = true;
3921
3922 // First, handle first-class matrix operations (* and matrix/scalar)
3923 switch (op) {
3924 case spv::OpFDiv:
3925 if (builder.isMatrix(left) && builder.isScalar(right)) {
3926 // turn matrix / scalar into a multiply...
3927 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3928 op = spv::OpMatrixTimesScalar;
3929 } else
3930 firstClass = false;
3931 break;
3932 case spv::OpMatrixTimesScalar:
3933 if (builder.isMatrix(right))
3934 std::swap(left, right);
3935 assert(builder.isScalar(right));
3936 break;
3937 case spv::OpVectorTimesMatrix:
3938 assert(builder.isVector(left));
3939 assert(builder.isMatrix(right));
3940 break;
3941 case spv::OpMatrixTimesVector:
3942 assert(builder.isMatrix(left));
3943 assert(builder.isVector(right));
3944 break;
3945 case spv::OpMatrixTimesMatrix:
3946 assert(builder.isMatrix(left));
3947 assert(builder.isMatrix(right));
3948 break;
3949 default:
3950 firstClass = false;
3951 break;
3952 }
3953
qining25262b32016-05-06 17:25:16 -04003954 if (firstClass) {
3955 spv::Id result = builder.createBinOp(op, typeId, left, right);
3956 addDecoration(result, noContraction);
3957 return builder.setPrecision(result, precision);
3958 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003959
LoopDawg592860c2016-06-09 08:57:35 -06003960 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003961 // The result type of all of them is the same type as the (a) matrix operand.
3962 // The algorithm is to:
3963 // - break the matrix(es) into vectors
3964 // - smear any scalar to a vector
3965 // - do vector operations
3966 // - make a matrix out the vector results
3967 switch (op) {
3968 case spv::OpFAdd:
3969 case spv::OpFSub:
3970 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003971 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003972 case spv::OpFMul:
3973 {
3974 // one time set up...
3975 bool leftMat = builder.isMatrix(left);
3976 bool rightMat = builder.isMatrix(right);
3977 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3978 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3979 spv::Id scalarType = builder.getScalarTypeId(typeId);
3980 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3981 std::vector<spv::Id> results;
3982 spv::Id smearVec = spv::NoResult;
3983 if (builder.isScalar(left))
3984 smearVec = builder.smearScalar(precision, left, vecType);
3985 else if (builder.isScalar(right))
3986 smearVec = builder.smearScalar(precision, right, vecType);
3987
3988 // do each vector op
3989 for (unsigned int c = 0; c < numCols; ++c) {
3990 std::vector<unsigned int> indexes;
3991 indexes.push_back(c);
3992 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3993 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003994 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3995 addDecoration(result, noContraction);
3996 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003997 }
3998
3999 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004000 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07004001 }
4002 default:
4003 assert(0);
4004 return spv::NoResult;
4005 }
4006}
4007
qining25262b32016-05-06 17:25:16 -04004008spv::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 -06004009{
4010 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004011 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004012 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004013#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004014 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004015 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4016#else
Rex Xucabbb782017-03-24 13:41:14 +08004017 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08004018 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004019#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004020
4021 switch (op) {
4022 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004023 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004024 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004025 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04004026 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004027 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004028 unaryOp = spv::OpSNegate;
4029 break;
4030
4031 case glslang::EOpLogicalNot:
4032 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004033 unaryOp = spv::OpLogicalNot;
4034 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004035 case glslang::EOpBitwiseNot:
4036 unaryOp = spv::OpNot;
4037 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004038
John Kessenich140f3df2015-06-26 16:58:36 -06004039 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004040 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004041 break;
4042 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004043 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004044 break;
4045 case glslang::EOpTranspose:
4046 unaryOp = spv::OpTranspose;
4047 break;
4048
4049 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004050 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004051 break;
4052 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004053 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004054 break;
4055 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004056 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004057 break;
4058 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004059 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004060 break;
4061 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004062 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004063 break;
4064 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004065 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004066 break;
4067 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004068 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004069 break;
4070 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004071 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004072 break;
4073
4074 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004075 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004076 break;
4077 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004078 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004079 break;
4080 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004081 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004082 break;
4083 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004084 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004085 break;
4086 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004087 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004088 break;
4089 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004090 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004091 break;
4092
4093 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004094 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004095 break;
4096 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004097 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004098 break;
4099
4100 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004101 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004102 break;
4103 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004104 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004105 break;
4106 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004107 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004108 break;
4109 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004110 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004111 break;
4112 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004113 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004114 break;
4115 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004116 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004117 break;
4118
4119 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004120 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004121 break;
4122 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004123 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004124 break;
4125 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004126 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004127 break;
4128 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004129 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004130 break;
4131 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004132 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004133 break;
4134 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004135 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004136 break;
4137
4138 case glslang::EOpIsNan:
4139 unaryOp = spv::OpIsNan;
4140 break;
4141 case glslang::EOpIsInf:
4142 unaryOp = spv::OpIsInf;
4143 break;
LoopDawg592860c2016-06-09 08:57:35 -06004144 case glslang::EOpIsFinite:
4145 unaryOp = spv::OpIsFinite;
4146 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004147
Rex Xucbc426e2015-12-15 16:03:10 +08004148 case glslang::EOpFloatBitsToInt:
4149 case glslang::EOpFloatBitsToUint:
4150 case glslang::EOpIntBitsToFloat:
4151 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004152 case glslang::EOpDoubleBitsToInt64:
4153 case glslang::EOpDoubleBitsToUint64:
4154 case glslang::EOpInt64BitsToDouble:
4155 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004156#ifdef AMD_EXTENSIONS
4157 case glslang::EOpFloat16BitsToInt16:
4158 case glslang::EOpFloat16BitsToUint16:
4159 case glslang::EOpInt16BitsToFloat16:
4160 case glslang::EOpUint16BitsToFloat16:
4161#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004162 unaryOp = spv::OpBitcast;
4163 break;
4164
John Kessenich140f3df2015-06-26 16:58:36 -06004165 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004166 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004167 break;
4168 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004169 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004170 break;
4171 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004172 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004173 break;
4174 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004175 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004176 break;
4177 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004178 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004179 break;
4180 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004181 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004182 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004183 case glslang::EOpPackSnorm4x8:
4184 libCall = spv::GLSLstd450PackSnorm4x8;
4185 break;
4186 case glslang::EOpUnpackSnorm4x8:
4187 libCall = spv::GLSLstd450UnpackSnorm4x8;
4188 break;
4189 case glslang::EOpPackUnorm4x8:
4190 libCall = spv::GLSLstd450PackUnorm4x8;
4191 break;
4192 case glslang::EOpUnpackUnorm4x8:
4193 libCall = spv::GLSLstd450UnpackUnorm4x8;
4194 break;
4195 case glslang::EOpPackDouble2x32:
4196 libCall = spv::GLSLstd450PackDouble2x32;
4197 break;
4198 case glslang::EOpUnpackDouble2x32:
4199 libCall = spv::GLSLstd450UnpackDouble2x32;
4200 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004201
Rex Xu8ff43de2016-04-22 16:51:45 +08004202 case glslang::EOpPackInt2x32:
4203 case glslang::EOpUnpackInt2x32:
4204 case glslang::EOpPackUint2x32:
4205 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004206 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004207 break;
4208
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004209#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004210 case glslang::EOpPackInt2x16:
4211 case glslang::EOpUnpackInt2x16:
4212 case glslang::EOpPackUint2x16:
4213 case glslang::EOpUnpackUint2x16:
4214 case glslang::EOpPackInt4x16:
4215 case glslang::EOpUnpackInt4x16:
4216 case glslang::EOpPackUint4x16:
4217 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004218 case glslang::EOpPackFloat2x16:
4219 case glslang::EOpUnpackFloat2x16:
4220 unaryOp = spv::OpBitcast;
4221 break;
4222#endif
4223
John Kessenich140f3df2015-06-26 16:58:36 -06004224 case glslang::EOpDPdx:
4225 unaryOp = spv::OpDPdx;
4226 break;
4227 case glslang::EOpDPdy:
4228 unaryOp = spv::OpDPdy;
4229 break;
4230 case glslang::EOpFwidth:
4231 unaryOp = spv::OpFwidth;
4232 break;
4233 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004234 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004235 unaryOp = spv::OpDPdxFine;
4236 break;
4237 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004238 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004239 unaryOp = spv::OpDPdyFine;
4240 break;
4241 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004242 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004243 unaryOp = spv::OpFwidthFine;
4244 break;
4245 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004246 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004247 unaryOp = spv::OpDPdxCoarse;
4248 break;
4249 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004250 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004251 unaryOp = spv::OpDPdyCoarse;
4252 break;
4253 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004254 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004255 unaryOp = spv::OpFwidthCoarse;
4256 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004257 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004258 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004259 libCall = spv::GLSLstd450InterpolateAtCentroid;
4260 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004261 case glslang::EOpAny:
4262 unaryOp = spv::OpAny;
4263 break;
4264 case glslang::EOpAll:
4265 unaryOp = spv::OpAll;
4266 break;
4267
4268 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004269 if (isFloat)
4270 libCall = spv::GLSLstd450FAbs;
4271 else
4272 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004273 break;
4274 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004275 if (isFloat)
4276 libCall = spv::GLSLstd450FSign;
4277 else
4278 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004279 break;
4280
John Kessenichfc51d282015-08-19 13:34:18 -06004281 case glslang::EOpAtomicCounterIncrement:
4282 case glslang::EOpAtomicCounterDecrement:
4283 case glslang::EOpAtomicCounter:
4284 {
4285 // Handle all of the atomics in one place, in createAtomicOperation()
4286 std::vector<spv::Id> operands;
4287 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004288 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004289 }
4290
John Kessenichfc51d282015-08-19 13:34:18 -06004291 case glslang::EOpBitFieldReverse:
4292 unaryOp = spv::OpBitReverse;
4293 break;
4294 case glslang::EOpBitCount:
4295 unaryOp = spv::OpBitCount;
4296 break;
4297 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004298 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004299 break;
4300 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004301 if (isUnsigned)
4302 libCall = spv::GLSLstd450FindUMsb;
4303 else
4304 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004305 break;
4306
Rex Xu574ab042016-04-14 16:53:07 +08004307 case glslang::EOpBallot:
4308 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004309 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004310 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004311 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004312#ifdef AMD_EXTENSIONS
4313 case glslang::EOpMinInvocations:
4314 case glslang::EOpMaxInvocations:
4315 case glslang::EOpAddInvocations:
4316 case glslang::EOpMinInvocationsNonUniform:
4317 case glslang::EOpMaxInvocationsNonUniform:
4318 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004319 case glslang::EOpMinInvocationsInclusiveScan:
4320 case glslang::EOpMaxInvocationsInclusiveScan:
4321 case glslang::EOpAddInvocationsInclusiveScan:
4322 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4323 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4324 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4325 case glslang::EOpMinInvocationsExclusiveScan:
4326 case glslang::EOpMaxInvocationsExclusiveScan:
4327 case glslang::EOpAddInvocationsExclusiveScan:
4328 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4329 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4330 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004331#endif
Rex Xu51596642016-09-21 18:56:12 +08004332 {
4333 std::vector<spv::Id> operands;
4334 operands.push_back(operand);
4335 return createInvocationsOperation(op, typeId, operands, typeProxy);
4336 }
Rex Xu9d93a232016-05-05 12:30:44 +08004337
4338#ifdef AMD_EXTENSIONS
4339 case glslang::EOpMbcnt:
4340 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4341 libCall = spv::MbcntAMD;
4342 break;
4343
4344 case glslang::EOpCubeFaceIndex:
4345 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4346 libCall = spv::CubeFaceIndexAMD;
4347 break;
4348
4349 case glslang::EOpCubeFaceCoord:
4350 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4351 libCall = spv::CubeFaceCoordAMD;
4352 break;
4353#endif
Rex Xu338b1852016-05-05 20:38:33 +08004354
John Kessenich140f3df2015-06-26 16:58:36 -06004355 default:
4356 return 0;
4357 }
4358
4359 spv::Id id;
4360 if (libCall >= 0) {
4361 std::vector<spv::Id> args;
4362 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004363 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004364 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004365 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004366 }
John Kessenich140f3df2015-06-26 16:58:36 -06004367
qining25262b32016-05-06 17:25:16 -04004368 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004369 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004370}
4371
John Kessenich7a53f762016-01-20 11:19:27 -07004372// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004373spv::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 -07004374{
4375 // Handle unary operations vector by vector.
4376 // The result type is the same type as the original type.
4377 // The algorithm is to:
4378 // - break the matrix into vectors
4379 // - apply the operation to each vector
4380 // - make a matrix out the vector results
4381
4382 // get the types sorted out
4383 int numCols = builder.getNumColumns(operand);
4384 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004385 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4386 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004387 std::vector<spv::Id> results;
4388
4389 // do each vector op
4390 for (int c = 0; c < numCols; ++c) {
4391 std::vector<unsigned int> indexes;
4392 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004393 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4394 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4395 addDecoration(destVec, noContraction);
4396 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004397 }
4398
4399 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004400 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004401}
4402
Rex Xu73e3ce72016-04-27 18:48:17 +08004403spv::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 -06004404{
4405 spv::Op convOp = spv::OpNop;
4406 spv::Id zero = 0;
4407 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004408 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004409
4410 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4411
4412 switch (op) {
4413 case glslang::EOpConvIntToBool:
4414 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004415 case glslang::EOpConvInt64ToBool:
4416 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004417#ifdef AMD_EXTENSIONS
4418 case glslang::EOpConvInt16ToBool:
4419 case glslang::EOpConvUint16ToBool:
4420#endif
4421 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4422 zero = builder.makeUint64Constant(0);
4423#ifdef AMD_EXTENSIONS
4424 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4425 zero = builder.makeUint16Constant(0);
4426#endif
4427 else
4428 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004429 zero = makeSmearedConstant(zero, vectorSize);
4430 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4431
4432 case glslang::EOpConvFloatToBool:
4433 zero = builder.makeFloatConstant(0.0F);
4434 zero = makeSmearedConstant(zero, vectorSize);
4435 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4436
4437 case glslang::EOpConvDoubleToBool:
4438 zero = builder.makeDoubleConstant(0.0);
4439 zero = makeSmearedConstant(zero, vectorSize);
4440 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4441
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004442#ifdef AMD_EXTENSIONS
4443 case glslang::EOpConvFloat16ToBool:
4444 zero = builder.makeFloat16Constant(0.0F);
4445 zero = makeSmearedConstant(zero, vectorSize);
4446 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4447#endif
4448
John Kessenich140f3df2015-06-26 16:58:36 -06004449 case glslang::EOpConvBoolToFloat:
4450 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004451 zero = builder.makeFloatConstant(0.0F);
4452 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004453 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004454
John Kessenich140f3df2015-06-26 16:58:36 -06004455 case glslang::EOpConvBoolToDouble:
4456 convOp = spv::OpSelect;
4457 zero = builder.makeDoubleConstant(0.0);
4458 one = builder.makeDoubleConstant(1.0);
4459 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004460
4461#ifdef AMD_EXTENSIONS
4462 case glslang::EOpConvBoolToFloat16:
4463 convOp = spv::OpSelect;
4464 zero = builder.makeFloat16Constant(0.0F);
4465 one = builder.makeFloat16Constant(1.0F);
4466 break;
4467#endif
4468
John Kessenich140f3df2015-06-26 16:58:36 -06004469 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004470 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004471#ifdef AMD_EXTENSIONS
4472 case glslang::EOpConvBoolToInt16:
4473#endif
4474 if (op == glslang::EOpConvBoolToInt64)
4475 zero = builder.makeInt64Constant(0);
4476#ifdef AMD_EXTENSIONS
4477 else if (op == glslang::EOpConvBoolToInt16)
4478 zero = builder.makeInt16Constant(0);
4479#endif
4480 else
4481 zero = builder.makeIntConstant(0);
4482
4483 if (op == glslang::EOpConvBoolToInt64)
4484 one = builder.makeInt64Constant(1);
4485#ifdef AMD_EXTENSIONS
4486 else if (op == glslang::EOpConvBoolToInt16)
4487 one = builder.makeInt16Constant(1);
4488#endif
4489 else
4490 one = builder.makeIntConstant(1);
4491
John Kessenich140f3df2015-06-26 16:58:36 -06004492 convOp = spv::OpSelect;
4493 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004494
John Kessenich140f3df2015-06-26 16:58:36 -06004495 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004496 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004497#ifdef AMD_EXTENSIONS
4498 case glslang::EOpConvBoolToUint16:
4499#endif
4500 if (op == glslang::EOpConvBoolToUint64)
4501 zero = builder.makeUint64Constant(0);
4502#ifdef AMD_EXTENSIONS
4503 else if (op == glslang::EOpConvBoolToUint16)
4504 zero = builder.makeUint16Constant(0);
4505#endif
4506 else
4507 zero = builder.makeUintConstant(0);
4508
4509 if (op == glslang::EOpConvBoolToUint64)
4510 one = builder.makeUint64Constant(1);
4511#ifdef AMD_EXTENSIONS
4512 else if (op == glslang::EOpConvBoolToUint16)
4513 one = builder.makeUint16Constant(1);
4514#endif
4515 else
4516 one = builder.makeUintConstant(1);
4517
John Kessenich140f3df2015-06-26 16:58:36 -06004518 convOp = spv::OpSelect;
4519 break;
4520
4521 case glslang::EOpConvIntToFloat:
4522 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004523 case glslang::EOpConvInt64ToFloat:
4524 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004525#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004526 case glslang::EOpConvInt16ToFloat:
4527 case glslang::EOpConvInt16ToDouble:
4528 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004529 case glslang::EOpConvIntToFloat16:
4530 case glslang::EOpConvInt64ToFloat16:
4531#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004532 convOp = spv::OpConvertSToF;
4533 break;
4534
4535 case glslang::EOpConvUintToFloat:
4536 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004537 case glslang::EOpConvUint64ToFloat:
4538 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004539#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004540 case glslang::EOpConvUint16ToFloat:
4541 case glslang::EOpConvUint16ToDouble:
4542 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004543 case glslang::EOpConvUintToFloat16:
4544 case glslang::EOpConvUint64ToFloat16:
4545#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004546 convOp = spv::OpConvertUToF;
4547 break;
4548
4549 case glslang::EOpConvDoubleToFloat:
4550 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004551#ifdef AMD_EXTENSIONS
4552 case glslang::EOpConvDoubleToFloat16:
4553 case glslang::EOpConvFloat16ToDouble:
4554 case glslang::EOpConvFloatToFloat16:
4555 case glslang::EOpConvFloat16ToFloat:
4556#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004557 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004558 if (builder.isMatrixType(destType))
4559 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004560 break;
4561
4562 case glslang::EOpConvFloatToInt:
4563 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004564 case glslang::EOpConvFloatToInt64:
4565 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004566#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004567 case glslang::EOpConvFloatToInt16:
4568 case glslang::EOpConvDoubleToInt16:
4569 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004570 case glslang::EOpConvFloat16ToInt:
4571 case glslang::EOpConvFloat16ToInt64:
4572#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004573 convOp = spv::OpConvertFToS;
4574 break;
4575
4576 case glslang::EOpConvUintToInt:
4577 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004578 case glslang::EOpConvUint64ToInt64:
4579 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004580#ifdef AMD_EXTENSIONS
4581 case glslang::EOpConvUint16ToInt16:
4582 case glslang::EOpConvInt16ToUint16:
4583#endif
qininge24aa5e2016-04-07 15:40:27 -04004584 if (builder.isInSpecConstCodeGenMode()) {
4585 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004586 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4587 zero = builder.makeUint64Constant(0);
4588#ifdef AMD_EXTENSIONS
4589 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4590 zero = builder.makeUint16Constant(0);
4591#endif
4592 else
4593 zero = builder.makeUintConstant(0);
4594
qining189b2032016-04-12 23:16:20 -04004595 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004596 // Use OpIAdd, instead of OpBitcast to do the conversion when
4597 // generating for OpSpecConstantOp instruction.
4598 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4599 }
4600 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004601 convOp = spv::OpBitcast;
4602 break;
4603
4604 case glslang::EOpConvFloatToUint:
4605 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004606 case glslang::EOpConvFloatToUint64:
4607 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004608#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004609 case glslang::EOpConvFloatToUint16:
4610 case glslang::EOpConvDoubleToUint16:
4611 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004612 case glslang::EOpConvFloat16ToUint:
4613 case glslang::EOpConvFloat16ToUint64:
4614#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004615 convOp = spv::OpConvertFToU;
4616 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004617
4618 case glslang::EOpConvIntToInt64:
4619 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004620#ifdef AMD_EXTENSIONS
4621 case glslang::EOpConvIntToInt16:
4622 case glslang::EOpConvInt16ToInt:
4623 case glslang::EOpConvInt64ToInt16:
4624 case glslang::EOpConvInt16ToInt64:
4625#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004626 convOp = spv::OpSConvert;
4627 break;
4628
4629 case glslang::EOpConvUintToUint64:
4630 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004631#ifdef AMD_EXTENSIONS
4632 case glslang::EOpConvUintToUint16:
4633 case glslang::EOpConvUint16ToUint:
4634 case glslang::EOpConvUint64ToUint16:
4635 case glslang::EOpConvUint16ToUint64:
4636#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004637 convOp = spv::OpUConvert;
4638 break;
4639
4640 case glslang::EOpConvIntToUint64:
4641 case glslang::EOpConvInt64ToUint:
4642 case glslang::EOpConvUint64ToInt:
4643 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004644#ifdef AMD_EXTENSIONS
4645 case glslang::EOpConvInt16ToUint:
4646 case glslang::EOpConvUintToInt16:
4647 case glslang::EOpConvInt16ToUint64:
4648 case glslang::EOpConvUint64ToInt16:
4649 case glslang::EOpConvUint16ToInt:
4650 case glslang::EOpConvIntToUint16:
4651 case glslang::EOpConvUint16ToInt64:
4652 case glslang::EOpConvInt64ToUint16:
4653#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004654 // OpSConvert/OpUConvert + OpBitCast
4655 switch (op) {
4656 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004657#ifdef AMD_EXTENSIONS
4658 case glslang::EOpConvInt16ToUint64:
4659#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004660 convOp = spv::OpSConvert;
4661 type = builder.makeIntType(64);
4662 break;
4663 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004664#ifdef AMD_EXTENSIONS
4665 case glslang::EOpConvInt16ToUint:
4666#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004667 convOp = spv::OpSConvert;
4668 type = builder.makeIntType(32);
4669 break;
4670 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004671#ifdef AMD_EXTENSIONS
4672 case glslang::EOpConvUint16ToInt:
4673#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004674 convOp = spv::OpUConvert;
4675 type = builder.makeUintType(32);
4676 break;
4677 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004678#ifdef AMD_EXTENSIONS
4679 case glslang::EOpConvUint16ToInt64:
4680#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004681 convOp = spv::OpUConvert;
4682 type = builder.makeUintType(64);
4683 break;
Rex Xucabbb782017-03-24 13:41:14 +08004684#ifdef AMD_EXTENSIONS
4685 case glslang::EOpConvUintToInt16:
4686 case glslang::EOpConvUint64ToInt16:
4687 convOp = spv::OpUConvert;
4688 type = builder.makeUintType(16);
4689 break;
4690 case glslang::EOpConvIntToUint16:
4691 case glslang::EOpConvInt64ToUint16:
4692 convOp = spv::OpSConvert;
4693 type = builder.makeIntType(16);
4694 break;
4695#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004696 default:
4697 assert(0);
4698 break;
4699 }
4700
4701 if (vectorSize > 0)
4702 type = builder.makeVectorType(type, vectorSize);
4703
4704 operand = builder.createUnaryOp(convOp, type, operand);
4705
4706 if (builder.isInSpecConstCodeGenMode()) {
4707 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004708#ifdef AMD_EXTENSIONS
4709 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4710 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4711 zero = builder.makeUint64Constant(0);
4712 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4713 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4714 zero = builder.makeUint16Constant(0);
4715 else
4716 zero = builder.makeUintConstant(0);
4717#else
4718 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4719 zero = builder.makeUint64Constant(0);
4720 else
4721 zero = builder.makeUintConstant(0);
4722#endif
4723
Rex Xu8ff43de2016-04-22 16:51:45 +08004724 zero = makeSmearedConstant(zero, vectorSize);
4725 // Use OpIAdd, instead of OpBitcast to do the conversion when
4726 // generating for OpSpecConstantOp instruction.
4727 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4728 }
4729 // For normal run-time conversion instruction, use OpBitcast.
4730 convOp = spv::OpBitcast;
4731 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004732 default:
4733 break;
4734 }
4735
4736 spv::Id result = 0;
4737 if (convOp == spv::OpNop)
4738 return result;
4739
4740 if (convOp == spv::OpSelect) {
4741 zero = makeSmearedConstant(zero, vectorSize);
4742 one = makeSmearedConstant(one, vectorSize);
4743 result = builder.createTriOp(convOp, destType, operand, one, zero);
4744 } else
4745 result = builder.createUnaryOp(convOp, destType, operand);
4746
John Kessenich32cfd492016-02-02 12:37:46 -07004747 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004748}
4749
4750spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4751{
4752 if (vectorSize == 0)
4753 return constant;
4754
4755 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4756 std::vector<spv::Id> components;
4757 for (int c = 0; c < vectorSize; ++c)
4758 components.push_back(constant);
4759 return builder.makeCompositeConstant(vectorTypeId, components);
4760}
4761
John Kessenich426394d2015-07-23 10:22:48 -06004762// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004763spv::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 -06004764{
4765 spv::Op opCode = spv::OpNop;
4766
4767 switch (op) {
4768 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004769 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004770 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004771 opCode = spv::OpAtomicIAdd;
4772 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004773 case glslang::EOpAtomicCounterSubtract:
4774 opCode = spv::OpAtomicISub;
4775 break;
John Kessenich426394d2015-07-23 10:22:48 -06004776 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004777 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004778 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08004779 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004780 break;
4781 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004782 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004783 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08004784 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004785 break;
4786 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004787 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004788 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004789 opCode = spv::OpAtomicAnd;
4790 break;
4791 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004792 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004793 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004794 opCode = spv::OpAtomicOr;
4795 break;
4796 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004797 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004798 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004799 opCode = spv::OpAtomicXor;
4800 break;
4801 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004802 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004803 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004804 opCode = spv::OpAtomicExchange;
4805 break;
4806 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004807 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004808 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004809 opCode = spv::OpAtomicCompareExchange;
4810 break;
4811 case glslang::EOpAtomicCounterIncrement:
4812 opCode = spv::OpAtomicIIncrement;
4813 break;
4814 case glslang::EOpAtomicCounterDecrement:
4815 opCode = spv::OpAtomicIDecrement;
4816 break;
4817 case glslang::EOpAtomicCounter:
4818 opCode = spv::OpAtomicLoad;
4819 break;
4820 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004821 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004822 break;
4823 }
4824
Rex Xue8fe8b02017-09-26 15:42:56 +08004825 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
4826 builder.addCapability(spv::CapabilityInt64Atomics);
4827
John Kessenich426394d2015-07-23 10:22:48 -06004828 // Sort out the operands
4829 // - mapping from glslang -> SPV
4830 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004831 // - compare-exchange swaps the value and comparator
4832 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004833 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4834 auto opIt = operands.begin(); // walk the glslang operands
4835 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004836 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4837 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4838 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004839 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4840 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004841 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004842 spvAtomicOperands.push_back(*(opIt + 1));
4843 spvAtomicOperands.push_back(*opIt);
4844 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004845 }
John Kessenich426394d2015-07-23 10:22:48 -06004846
John Kessenich3e60a6f2015-09-14 22:45:16 -06004847 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004848 for (; opIt != operands.end(); ++opIt)
4849 spvAtomicOperands.push_back(*opIt);
4850
4851 return builder.createOp(opCode, typeId, spvAtomicOperands);
4852}
4853
John Kessenich91cef522016-05-05 16:45:40 -06004854// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004855spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004856{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004857#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004858 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004859 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004860#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004861
Rex Xu51596642016-09-21 18:56:12 +08004862 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004863 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004864 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4865
chaocf200da82016-12-20 12:44:35 -08004866 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4867 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004868 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4869 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004870 } else if (op == glslang::EOpAnyInvocation ||
4871 op == glslang::EOpAllInvocations ||
4872 op == glslang::EOpAllInvocationsEqual) {
4873 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4874 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004875 } else {
4876 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004877#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004878 if (op == glslang::EOpMinInvocationsNonUniform ||
4879 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004880 op == glslang::EOpAddInvocationsNonUniform ||
4881 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4882 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4883 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4884 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4885 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4886 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004887 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004888#endif
Rex Xu51596642016-09-21 18:56:12 +08004889
4890 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004891#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004892 switch (op) {
4893 case glslang::EOpMinInvocations:
4894 case glslang::EOpMaxInvocations:
4895 case glslang::EOpAddInvocations:
4896 case glslang::EOpMinInvocationsNonUniform:
4897 case glslang::EOpMaxInvocationsNonUniform:
4898 case glslang::EOpAddInvocationsNonUniform:
4899 groupOperation = spv::GroupOperationReduce;
4900 spvGroupOperands.push_back(groupOperation);
4901 break;
4902 case glslang::EOpMinInvocationsInclusiveScan:
4903 case glslang::EOpMaxInvocationsInclusiveScan:
4904 case glslang::EOpAddInvocationsInclusiveScan:
4905 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4906 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4907 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4908 groupOperation = spv::GroupOperationInclusiveScan;
4909 spvGroupOperands.push_back(groupOperation);
4910 break;
4911 case glslang::EOpMinInvocationsExclusiveScan:
4912 case glslang::EOpMaxInvocationsExclusiveScan:
4913 case glslang::EOpAddInvocationsExclusiveScan:
4914 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4915 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4916 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4917 groupOperation = spv::GroupOperationExclusiveScan;
4918 spvGroupOperands.push_back(groupOperation);
4919 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004920 default:
4921 break;
Rex Xu430ef402016-10-14 17:22:23 +08004922 }
Rex Xu9d93a232016-05-05 12:30:44 +08004923#endif
Rex Xu51596642016-09-21 18:56:12 +08004924 }
4925
4926 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4927 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004928
4929 switch (op) {
4930 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004931 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004932 break;
John Kessenich91cef522016-05-05 16:45:40 -06004933 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004934 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004935 break;
John Kessenich91cef522016-05-05 16:45:40 -06004936 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004937 opCode = spv::OpSubgroupAllEqualKHR;
4938 break;
Rex Xu51596642016-09-21 18:56:12 +08004939 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004940 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004941 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004942 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004943 break;
4944 case glslang::EOpReadFirstInvocation:
4945 opCode = spv::OpSubgroupFirstInvocationKHR;
4946 break;
4947 case glslang::EOpBallot:
4948 {
4949 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4950 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4951 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4952 //
4953 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4954 //
4955 spv::Id uintType = builder.makeUintType(32);
4956 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4957 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4958
4959 std::vector<spv::Id> components;
4960 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4961 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4962
4963 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4964 return builder.createUnaryOp(spv::OpBitcast, typeId,
4965 builder.createCompositeConstruct(uvec2Type, components));
4966 }
4967
Rex Xu9d93a232016-05-05 12:30:44 +08004968#ifdef AMD_EXTENSIONS
4969 case glslang::EOpMinInvocations:
4970 case glslang::EOpMaxInvocations:
4971 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004972 case glslang::EOpMinInvocationsInclusiveScan:
4973 case glslang::EOpMaxInvocationsInclusiveScan:
4974 case glslang::EOpAddInvocationsInclusiveScan:
4975 case glslang::EOpMinInvocationsExclusiveScan:
4976 case glslang::EOpMaxInvocationsExclusiveScan:
4977 case glslang::EOpAddInvocationsExclusiveScan:
4978 if (op == glslang::EOpMinInvocations ||
4979 op == glslang::EOpMinInvocationsInclusiveScan ||
4980 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004981 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004982 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004983 else {
4984 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004985 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004986 else
Rex Xu51596642016-09-21 18:56:12 +08004987 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004988 }
Rex Xu430ef402016-10-14 17:22:23 +08004989 } else if (op == glslang::EOpMaxInvocations ||
4990 op == glslang::EOpMaxInvocationsInclusiveScan ||
4991 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004992 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004993 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004994 else {
4995 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004996 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004997 else
Rex Xu51596642016-09-21 18:56:12 +08004998 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004999 }
5000 } else {
5001 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005002 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005003 else
Rex Xu51596642016-09-21 18:56:12 +08005004 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005005 }
5006
Rex Xu2bbbe062016-08-23 15:41:05 +08005007 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005008 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005009
5010 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005011 case glslang::EOpMinInvocationsNonUniform:
5012 case glslang::EOpMaxInvocationsNonUniform:
5013 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005014 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5015 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5016 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5017 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5018 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5019 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5020 if (op == glslang::EOpMinInvocationsNonUniform ||
5021 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5022 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005023 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005024 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005025 else {
5026 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005027 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005028 else
Rex Xu51596642016-09-21 18:56:12 +08005029 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005030 }
5031 }
Rex Xu430ef402016-10-14 17:22:23 +08005032 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5033 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5034 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005035 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005036 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005037 else {
5038 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005039 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005040 else
Rex Xu51596642016-09-21 18:56:12 +08005041 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005042 }
5043 }
5044 else {
5045 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005046 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005047 else
Rex Xu51596642016-09-21 18:56:12 +08005048 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005049 }
5050
Rex Xu2bbbe062016-08-23 15:41:05 +08005051 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005052 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005053
5054 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005055#endif
John Kessenich91cef522016-05-05 16:45:40 -06005056 default:
5057 logger->missingFunctionality("invocation operation");
5058 return spv::NoResult;
5059 }
Rex Xu51596642016-09-21 18:56:12 +08005060
5061 assert(opCode != spv::OpNop);
5062 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005063}
5064
Rex Xu2bbbe062016-08-23 15:41:05 +08005065// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005066spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005067{
Rex Xub7072052016-09-26 15:53:40 +08005068#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005069 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5070 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005071 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005072 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005073 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5074 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5075 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005076#else
5077 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5078 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005079 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5080 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005081#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005082
5083 // Handle group invocation operations scalar by scalar.
5084 // The result type is the same type as the original type.
5085 // The algorithm is to:
5086 // - break the vector into scalars
5087 // - apply the operation to each scalar
5088 // - make a vector out the scalar results
5089
5090 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005091 int numComponents = builder.getNumComponents(operands[0]);
5092 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005093 std::vector<spv::Id> results;
5094
5095 // do each scalar op
5096 for (int comp = 0; comp < numComponents; ++comp) {
5097 std::vector<unsigned int> indexes;
5098 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005099 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005100 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005101 if (op == spv::OpSubgroupReadInvocationKHR) {
5102 spvGroupOperands.push_back(scalar);
5103 spvGroupOperands.push_back(operands[1]);
5104 } else if (op == spv::OpGroupBroadcast) {
5105 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005106 spvGroupOperands.push_back(scalar);
5107 spvGroupOperands.push_back(operands[1]);
5108 } else {
chaocf200da82016-12-20 12:44:35 -08005109 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005110 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005111 spvGroupOperands.push_back(scalar);
5112 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005113
Rex Xub7072052016-09-26 15:53:40 +08005114 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005115 }
5116
5117 // put the pieces together
5118 return builder.createCompositeConstruct(typeId, results);
5119}
Rex Xu2bbbe062016-08-23 15:41:05 +08005120
John Kessenich5e4b1242015-08-06 22:53:06 -06005121spv::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 -06005122{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005123#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005124 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005125 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5126#else
Rex Xucabbb782017-03-24 13:41:14 +08005127 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005128 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005129#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005130
John Kessenich140f3df2015-06-26 16:58:36 -06005131 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005132 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005133 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005134 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005135 spv::Id typeId0 = 0;
5136 if (consumedOperands > 0)
5137 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005138 spv::Id typeId1 = 0;
5139 if (consumedOperands > 1)
5140 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005141 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005142
5143 switch (op) {
5144 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005145 if (isFloat)
5146 libCall = spv::GLSLstd450FMin;
5147 else if (isUnsigned)
5148 libCall = spv::GLSLstd450UMin;
5149 else
5150 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005151 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005152 break;
5153 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005154 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005155 break;
5156 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005157 if (isFloat)
5158 libCall = spv::GLSLstd450FMax;
5159 else if (isUnsigned)
5160 libCall = spv::GLSLstd450UMax;
5161 else
5162 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005163 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005164 break;
5165 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005166 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005167 break;
5168 case glslang::EOpDot:
5169 opCode = spv::OpDot;
5170 break;
5171 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005172 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005173 break;
5174
5175 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005176 if (isFloat)
5177 libCall = spv::GLSLstd450FClamp;
5178 else if (isUnsigned)
5179 libCall = spv::GLSLstd450UClamp;
5180 else
5181 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005182 builder.promoteScalar(precision, operands.front(), operands[1]);
5183 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005184 break;
5185 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005186 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5187 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005188 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005189 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005190 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005191 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005192 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005193 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005194 break;
5195 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005196 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005197 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005198 break;
5199 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005200 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005201 builder.promoteScalar(precision, operands[0], operands[2]);
5202 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005203 break;
5204
5205 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005206 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005207 break;
5208 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005209 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005210 break;
5211 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005212 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005213 break;
5214 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005215 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005216 break;
5217 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005218 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005219 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005220 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005221 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005222 libCall = spv::GLSLstd450InterpolateAtSample;
5223 break;
5224 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005225 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005226 libCall = spv::GLSLstd450InterpolateAtOffset;
5227 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005228 case glslang::EOpAddCarry:
5229 opCode = spv::OpIAddCarry;
5230 typeId = builder.makeStructResultType(typeId0, typeId0);
5231 consumedOperands = 2;
5232 break;
5233 case glslang::EOpSubBorrow:
5234 opCode = spv::OpISubBorrow;
5235 typeId = builder.makeStructResultType(typeId0, typeId0);
5236 consumedOperands = 2;
5237 break;
5238 case glslang::EOpUMulExtended:
5239 opCode = spv::OpUMulExtended;
5240 typeId = builder.makeStructResultType(typeId0, typeId0);
5241 consumedOperands = 2;
5242 break;
5243 case glslang::EOpIMulExtended:
5244 opCode = spv::OpSMulExtended;
5245 typeId = builder.makeStructResultType(typeId0, typeId0);
5246 consumedOperands = 2;
5247 break;
5248 case glslang::EOpBitfieldExtract:
5249 if (isUnsigned)
5250 opCode = spv::OpBitFieldUExtract;
5251 else
5252 opCode = spv::OpBitFieldSExtract;
5253 break;
5254 case glslang::EOpBitfieldInsert:
5255 opCode = spv::OpBitFieldInsert;
5256 break;
5257
5258 case glslang::EOpFma:
5259 libCall = spv::GLSLstd450Fma;
5260 break;
5261 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005262 {
5263 libCall = spv::GLSLstd450FrexpStruct;
5264 assert(builder.isPointerType(typeId1));
5265 typeId1 = builder.getContainedTypeId(typeId1);
5266#ifdef AMD_EXTENSIONS
5267 int width = builder.getScalarTypeWidth(typeId1);
5268#else
5269 int width = 32;
5270#endif
5271 if (builder.getNumComponents(operands[0]) == 1)
5272 frexpIntType = builder.makeIntegerType(width, true);
5273 else
5274 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5275 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5276 consumedOperands = 1;
5277 }
John Kessenich55e7d112015-11-15 21:33:39 -07005278 break;
5279 case glslang::EOpLdexp:
5280 libCall = spv::GLSLstd450Ldexp;
5281 break;
5282
Rex Xu574ab042016-04-14 16:53:07 +08005283 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005284 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005285
Rex Xu9d93a232016-05-05 12:30:44 +08005286#ifdef AMD_EXTENSIONS
5287 case glslang::EOpSwizzleInvocations:
5288 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5289 libCall = spv::SwizzleInvocationsAMD;
5290 break;
5291 case glslang::EOpSwizzleInvocationsMasked:
5292 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5293 libCall = spv::SwizzleInvocationsMaskedAMD;
5294 break;
5295 case glslang::EOpWriteInvocation:
5296 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5297 libCall = spv::WriteInvocationAMD;
5298 break;
5299
5300 case glslang::EOpMin3:
5301 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5302 if (isFloat)
5303 libCall = spv::FMin3AMD;
5304 else {
5305 if (isUnsigned)
5306 libCall = spv::UMin3AMD;
5307 else
5308 libCall = spv::SMin3AMD;
5309 }
5310 break;
5311 case glslang::EOpMax3:
5312 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5313 if (isFloat)
5314 libCall = spv::FMax3AMD;
5315 else {
5316 if (isUnsigned)
5317 libCall = spv::UMax3AMD;
5318 else
5319 libCall = spv::SMax3AMD;
5320 }
5321 break;
5322 case glslang::EOpMid3:
5323 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5324 if (isFloat)
5325 libCall = spv::FMid3AMD;
5326 else {
5327 if (isUnsigned)
5328 libCall = spv::UMid3AMD;
5329 else
5330 libCall = spv::SMid3AMD;
5331 }
5332 break;
5333
5334 case glslang::EOpInterpolateAtVertex:
5335 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5336 libCall = spv::InterpolateAtVertexAMD;
5337 break;
5338#endif
5339
John Kessenich140f3df2015-06-26 16:58:36 -06005340 default:
5341 return 0;
5342 }
5343
5344 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005345 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005346 // Use an extended instruction from the standard library.
5347 // Construct the call arguments, without modifying the original operands vector.
5348 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5349 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005350 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005351 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005352 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005353 case 0:
5354 // should all be handled by visitAggregate and createNoArgOperation
5355 assert(0);
5356 return 0;
5357 case 1:
5358 // should all be handled by createUnaryOperation
5359 assert(0);
5360 return 0;
5361 case 2:
5362 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5363 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005364 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005365 // anything 3 or over doesn't have l-value operands, so all should be consumed
5366 assert(consumedOperands == operands.size());
5367 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005368 break;
5369 }
5370 }
5371
John Kessenich55e7d112015-11-15 21:33:39 -07005372 // Decode the return types that were structures
5373 switch (op) {
5374 case glslang::EOpAddCarry:
5375 case glslang::EOpSubBorrow:
5376 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5377 id = builder.createCompositeExtract(id, typeId0, 0);
5378 break;
5379 case glslang::EOpUMulExtended:
5380 case glslang::EOpIMulExtended:
5381 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5382 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5383 break;
5384 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005385 {
5386 assert(operands.size() == 2);
5387 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5388 // "exp" is floating-point type (from HLSL intrinsic)
5389 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5390 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5391 builder.createStore(member1, operands[1]);
5392 } else
5393 // "exp" is integer type (from GLSL built-in function)
5394 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5395 id = builder.createCompositeExtract(id, typeId0, 0);
5396 }
John Kessenich55e7d112015-11-15 21:33:39 -07005397 break;
5398 default:
5399 break;
5400 }
5401
John Kessenich32cfd492016-02-02 12:37:46 -07005402 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005403}
5404
Rex Xu9d93a232016-05-05 12:30:44 +08005405// Intrinsics with no arguments (or no return value, and no precision).
5406spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005407{
5408 // TODO: get the barrier operands correct
5409
5410 switch (op) {
5411 case glslang::EOpEmitVertex:
5412 builder.createNoResultOp(spv::OpEmitVertex);
5413 return 0;
5414 case glslang::EOpEndPrimitive:
5415 builder.createNoResultOp(spv::OpEndPrimitive);
5416 return 0;
5417 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005418 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005419 return 0;
5420 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005421 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005422 return 0;
5423 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005424 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005425 return 0;
5426 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005427 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005428 return 0;
5429 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005430 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005431 return 0;
5432 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005433 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005434 return 0;
5435 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005436 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005437 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005438 case glslang::EOpAllMemoryBarrierWithGroupSync:
5439 // Control barrier with non-"None" semantic is also a memory barrier.
5440 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5441 return 0;
5442 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5443 // Control barrier with non-"None" semantic is also a memory barrier.
5444 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5445 return 0;
5446 case glslang::EOpWorkgroupMemoryBarrier:
5447 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5448 return 0;
5449 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5450 // Control barrier with non-"None" semantic is also a memory barrier.
5451 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5452 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005453#ifdef AMD_EXTENSIONS
5454 case glslang::EOpTime:
5455 {
5456 std::vector<spv::Id> args; // Dummy arguments
5457 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5458 return builder.setPrecision(id, precision);
5459 }
5460#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005461 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005462 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005463 return 0;
5464 }
5465}
5466
5467spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5468{
John Kessenich2f273362015-07-18 22:34:27 -06005469 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005470 spv::Id id;
5471 if (symbolValues.end() != iter) {
5472 id = iter->second;
5473 return id;
5474 }
5475
5476 // it was not found, create it
5477 id = createSpvVariable(symbol);
5478 symbolValues[symbol->getId()] = id;
5479
Rex Xuc884b4a2016-06-29 15:03:44 +08005480 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005481 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005482 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005483 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005484 if (symbol->getType().getQualifier().hasSpecConstantId())
5485 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005486 if (symbol->getQualifier().hasIndex())
5487 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5488 if (symbol->getQualifier().hasComponent())
5489 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5490 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005491 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005492 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005493 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005494 if (symbol->getQualifier().hasXfbBuffer())
5495 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5496 if (symbol->getQualifier().hasXfbOffset())
5497 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5498 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005499 // atomic counters use this:
5500 if (symbol->getQualifier().hasOffset())
5501 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005502 }
5503
scygan2c864272016-05-18 18:09:17 +02005504 if (symbol->getQualifier().hasLocation())
5505 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005506 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005507 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005508 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005509 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005510 }
John Kessenich140f3df2015-06-26 16:58:36 -06005511 if (symbol->getQualifier().hasSet())
5512 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005513 else if (IsDescriptorResource(symbol->getType())) {
5514 // default to 0
5515 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5516 }
John Kessenich140f3df2015-06-26 16:58:36 -06005517 if (symbol->getQualifier().hasBinding())
5518 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005519 if (symbol->getQualifier().hasAttachment())
5520 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005521 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005522 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005523 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005524 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005525 if (symbol->getQualifier().hasXfbBuffer())
5526 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5527 }
5528
Rex Xu1da878f2016-02-21 20:59:01 +08005529 if (symbol->getType().isImage()) {
5530 std::vector<spv::Decoration> memory;
5531 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5532 for (unsigned int i = 0; i < memory.size(); ++i)
5533 addDecoration(id, memory[i]);
5534 }
5535
John Kessenich140f3df2015-06-26 16:58:36 -06005536 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005537 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005538 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005539 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005540
John Kessenichecba76f2017-01-06 00:34:48 -07005541#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005542 if (builtIn == spv::BuiltInSampleMask) {
5543 spv::Decoration decoration;
5544 // GL_NV_sample_mask_override_coverage extension
5545 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005546 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005547 else
5548 decoration = (spv::Decoration)spv::DecorationMax;
5549 addDecoration(id, decoration);
5550 if (decoration != spv::DecorationMax) {
5551 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5552 }
5553 }
chaoc771d89f2017-01-13 01:10:53 -08005554 else if (builtIn == spv::BuiltInLayer) {
5555 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005556 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005557 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5558 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5559 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5560 }
John Kessenichb41bff62017-08-11 13:07:17 -06005561 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005562 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5563 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5564 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5565 }
5566 }
5567
chaoc6e5acae2016-12-20 13:28:52 -08005568 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005569 addDecoration(id, spv::DecorationPassthroughNV);
5570 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005571 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5572 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005573#endif
5574
John Kessenich140f3df2015-06-26 16:58:36 -06005575 return id;
5576}
5577
John Kessenich55e7d112015-11-15 21:33:39 -07005578// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005579void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5580{
John Kessenich4016e382016-07-15 11:53:56 -06005581 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005582 builder.addDecoration(id, dec);
5583}
5584
John Kessenich55e7d112015-11-15 21:33:39 -07005585// If 'dec' is valid, add a one-operand decoration to an object
5586void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5587{
John Kessenich4016e382016-07-15 11:53:56 -06005588 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005589 builder.addDecoration(id, dec, value);
5590}
5591
5592// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005593void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5594{
John Kessenich4016e382016-07-15 11:53:56 -06005595 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005596 builder.addMemberDecoration(id, (unsigned)member, dec);
5597}
5598
John Kessenich92187592016-02-01 13:45:25 -07005599// If 'dec' is valid, add a one-operand decoration to a struct member
5600void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5601{
John Kessenich4016e382016-07-15 11:53:56 -06005602 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005603 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5604}
5605
John Kessenich55e7d112015-11-15 21:33:39 -07005606// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005607// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005608//
5609// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5610//
5611// Recursively walk the nodes. The nodes form a tree whose leaves are
5612// regular constants, which themselves are trees that createSpvConstant()
5613// recursively walks. So, this function walks the "top" of the tree:
5614// - emit specialization constant-building instructions for specConstant
5615// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005616spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005617{
John Kessenich7cc0e282016-03-20 00:46:02 -06005618 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005619
qining4f4bb812016-04-03 23:55:17 -04005620 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005621 if (! node.getQualifier().specConstant) {
5622 // hand off to the non-spec-constant path
5623 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5624 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005625 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005626 nextConst, false);
5627 }
5628
5629 // We now know we have a specialization constant to build
5630
John Kessenichd94c0032016-05-30 19:29:40 -06005631 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005632 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5633 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5634 std::vector<spv::Id> dimConstId;
5635 for (int dim = 0; dim < 3; ++dim) {
5636 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5637 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5638 if (specConst)
5639 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5640 }
5641 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5642 }
5643
5644 // An AST node labelled as specialization constant should be a symbol node.
5645 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5646 if (auto* sn = node.getAsSymbolNode()) {
5647 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005648 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5649 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5650 // will set the builder into spec constant op instruction generating mode.
5651 sub_tree->traverse(this);
5652 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005653 } else if (auto* const_union_array = &sn->getConstArray()){
5654 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005655 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5656 builder.addName(id, sn->getName().c_str());
5657 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005658 }
5659 }
qining4f4bb812016-04-03 23:55:17 -04005660
5661 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5662 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005663 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005664 exit(1);
5665 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005666}
5667
John Kessenich140f3df2015-06-26 16:58:36 -06005668// Use 'consts' as the flattened glslang source of scalar constants to recursively
5669// build the aggregate SPIR-V constant.
5670//
5671// If there are not enough elements present in 'consts', 0 will be substituted;
5672// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5673//
qining08408382016-03-21 09:51:37 -04005674spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005675{
5676 // vector of constants for SPIR-V
5677 std::vector<spv::Id> spvConsts;
5678
5679 // Type is used for struct and array constants
5680 spv::Id typeId = convertGlslangToSpvType(glslangType);
5681
5682 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005683 glslang::TType elementType(glslangType, 0);
5684 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005685 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005686 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005687 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005688 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005689 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005690 } else if (glslangType.getStruct()) {
5691 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5692 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005693 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005694 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005695 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5696 bool zero = nextConst >= consts.size();
5697 switch (glslangType.getBasicType()) {
5698 case glslang::EbtInt:
5699 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5700 break;
5701 case glslang::EbtUint:
5702 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5703 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005704 case glslang::EbtInt64:
5705 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5706 break;
5707 case glslang::EbtUint64:
5708 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5709 break;
Rex Xucabbb782017-03-24 13:41:14 +08005710#ifdef AMD_EXTENSIONS
5711 case glslang::EbtInt16:
5712 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5713 break;
5714 case glslang::EbtUint16:
5715 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5716 break;
5717#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005718 case glslang::EbtFloat:
5719 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5720 break;
5721 case glslang::EbtDouble:
5722 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5723 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005724#ifdef AMD_EXTENSIONS
5725 case glslang::EbtFloat16:
5726 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5727 break;
5728#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005729 case glslang::EbtBool:
5730 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5731 break;
5732 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005733 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005734 break;
5735 }
5736 ++nextConst;
5737 }
5738 } else {
5739 // we have a non-aggregate (scalar) constant
5740 bool zero = nextConst >= consts.size();
5741 spv::Id scalar = 0;
5742 switch (glslangType.getBasicType()) {
5743 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005744 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005745 break;
5746 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005747 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005748 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005749 case glslang::EbtInt64:
5750 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5751 break;
5752 case glslang::EbtUint64:
5753 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5754 break;
Rex Xucabbb782017-03-24 13:41:14 +08005755#ifdef AMD_EXTENSIONS
5756 case glslang::EbtInt16:
5757 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5758 break;
5759 case glslang::EbtUint16:
5760 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5761 break;
5762#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005763 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005764 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005765 break;
5766 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005767 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005768 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005769#ifdef AMD_EXTENSIONS
5770 case glslang::EbtFloat16:
5771 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5772 break;
5773#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005774 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005775 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005776 break;
5777 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005778 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005779 break;
5780 }
5781 ++nextConst;
5782 return scalar;
5783 }
5784
5785 return builder.makeCompositeConstant(typeId, spvConsts);
5786}
5787
John Kessenich7c1aa102015-10-15 13:29:11 -06005788// Return true if the node is a constant or symbol whose reading has no
5789// non-trivial observable cost or effect.
5790bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5791{
5792 // don't know what this is
5793 if (node == nullptr)
5794 return false;
5795
5796 // a constant is safe
5797 if (node->getAsConstantUnion() != nullptr)
5798 return true;
5799
5800 // not a symbol means non-trivial
5801 if (node->getAsSymbolNode() == nullptr)
5802 return false;
5803
5804 // a symbol, depends on what's being read
5805 switch (node->getType().getQualifier().storage) {
5806 case glslang::EvqTemporary:
5807 case glslang::EvqGlobal:
5808 case glslang::EvqIn:
5809 case glslang::EvqInOut:
5810 case glslang::EvqConst:
5811 case glslang::EvqConstReadOnly:
5812 case glslang::EvqUniform:
5813 return true;
5814 default:
5815 return false;
5816 }
qining25262b32016-05-06 17:25:16 -04005817}
John Kessenich7c1aa102015-10-15 13:29:11 -06005818
5819// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005820// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005821// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005822// Return true if trivial.
5823bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5824{
5825 if (node == nullptr)
5826 return false;
5827
John Kessenich84cc15f2017-05-24 16:44:47 -06005828 // count non scalars as trivial, as well as anything coming from HLSL
5829 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005830 return true;
5831
John Kessenich7c1aa102015-10-15 13:29:11 -06005832 // symbols and constants are trivial
5833 if (isTrivialLeaf(node))
5834 return true;
5835
5836 // otherwise, it needs to be a simple operation or one or two leaf nodes
5837
5838 // not a simple operation
5839 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5840 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5841 if (binaryNode == nullptr && unaryNode == nullptr)
5842 return false;
5843
5844 // not on leaf nodes
5845 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5846 return false;
5847
5848 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5849 return false;
5850 }
5851
5852 switch (node->getAsOperator()->getOp()) {
5853 case glslang::EOpLogicalNot:
5854 case glslang::EOpConvIntToBool:
5855 case glslang::EOpConvUintToBool:
5856 case glslang::EOpConvFloatToBool:
5857 case glslang::EOpConvDoubleToBool:
5858 case glslang::EOpEqual:
5859 case glslang::EOpNotEqual:
5860 case glslang::EOpLessThan:
5861 case glslang::EOpGreaterThan:
5862 case glslang::EOpLessThanEqual:
5863 case glslang::EOpGreaterThanEqual:
5864 case glslang::EOpIndexDirect:
5865 case glslang::EOpIndexDirectStruct:
5866 case glslang::EOpLogicalXor:
5867 case glslang::EOpAny:
5868 case glslang::EOpAll:
5869 return true;
5870 default:
5871 return false;
5872 }
5873}
5874
5875// Emit short-circuiting code, where 'right' is never evaluated unless
5876// the left side is true (for &&) or false (for ||).
5877spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5878{
5879 spv::Id boolTypeId = builder.makeBoolType();
5880
5881 // emit left operand
5882 builder.clearAccessChain();
5883 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005884 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005885
5886 // Operands to accumulate OpPhi operands
5887 std::vector<spv::Id> phiOperands;
5888 // accumulate left operand's phi information
5889 phiOperands.push_back(leftId);
5890 phiOperands.push_back(builder.getBuildPoint()->getId());
5891
5892 // Make the two kinds of operation symmetric with a "!"
5893 // || => emit "if (! left) result = right"
5894 // && => emit "if ( left) result = right"
5895 //
5896 // TODO: this runtime "not" for || could be avoided by adding functionality
5897 // to 'builder' to have an "else" without an "then"
5898 if (op == glslang::EOpLogicalOr)
5899 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5900
5901 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005902 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005903
5904 // emit right operand as the "then" part of the "if"
5905 builder.clearAccessChain();
5906 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005907 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005908
5909 // accumulate left operand's phi information
5910 phiOperands.push_back(rightId);
5911 phiOperands.push_back(builder.getBuildPoint()->getId());
5912
5913 // finish the "if"
5914 ifBuilder.makeEndIf();
5915
5916 // phi together the two results
5917 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5918}
5919
Rex Xu9d93a232016-05-05 12:30:44 +08005920// Return type Id of the imported set of extended instructions corresponds to the name.
5921// Import this set if it has not been imported yet.
5922spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5923{
5924 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5925 return extBuiltinMap[name];
5926 else {
Rex Xu51596642016-09-21 18:56:12 +08005927 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005928 spv::Id extBuiltins = builder.import(name);
5929 extBuiltinMap[name] = extBuiltins;
5930 return extBuiltins;
5931 }
5932}
5933
John Kessenich140f3df2015-06-26 16:58:36 -06005934}; // end anonymous namespace
5935
5936namespace glslang {
5937
John Kessenich68d78fd2015-07-12 19:28:10 -06005938void GetSpirvVersion(std::string& version)
5939{
John Kessenich9e55f632015-07-15 10:03:39 -06005940 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005941 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005942 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005943 version = buf;
5944}
5945
John Kessenich140f3df2015-06-26 16:58:36 -06005946// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005947void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005948{
5949 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005950 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005951 if (out.fail())
5952 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005953 for (int i = 0; i < (int)spirv.size(); ++i) {
5954 unsigned int word = spirv[i];
5955 out.write((const char*)&word, 4);
5956 }
5957 out.close();
5958}
5959
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005960// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005961void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005962{
5963 std::ofstream out;
5964 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005965 if (out.fail())
5966 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005967 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005968 if (varName != nullptr) {
5969 out << "\t #pragma once" << std::endl;
5970 out << "const uint32_t " << varName << "[] = {" << std::endl;
5971 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005972 const int WORDS_PER_LINE = 8;
5973 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5974 out << "\t";
5975 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5976 const unsigned int word = spirv[i + j];
5977 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5978 if (i + j + 1 < (int)spirv.size()) {
5979 out << ",";
5980 }
5981 }
5982 out << std::endl;
5983 }
Flavio15017db2017-02-15 14:29:33 -08005984 if (varName != nullptr) {
5985 out << "};";
5986 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005987 out.close();
5988}
5989
GregFcd1f1692017-09-21 18:40:22 -06005990#ifdef ENABLE_OPT
5991void errHandler(const std::string& str) {
5992 std::cerr << str << std::endl;
5993}
5994#endif
5995
John Kessenich140f3df2015-06-26 16:58:36 -06005996//
5997// Set up the glslang traversal
5998//
John Kessenich121853f2017-05-31 17:11:16 -06005999void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006000{
Lei Zhang17535f72016-05-04 15:55:59 -04006001 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006002 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006003}
6004
John Kessenich121853f2017-05-31 17:11:16 -06006005void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6006 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006007{
John Kessenich140f3df2015-06-26 16:58:36 -06006008 TIntermNode* root = intermediate.getTreeRoot();
6009
6010 if (root == 0)
6011 return;
6012
John Kessenich121853f2017-05-31 17:11:16 -06006013 glslang::SpvOptions defaultOptions;
6014 if (options == nullptr)
6015 options = &defaultOptions;
6016
John Kessenich140f3df2015-06-26 16:58:36 -06006017 glslang::GetThreadPoolAllocator().push();
6018
John Kessenich121853f2017-05-31 17:11:16 -06006019 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006020 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006021 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006022 it.dumpSpv(spirv);
6023
GregFcd1f1692017-09-21 18:40:22 -06006024#ifdef ENABLE_OPT
6025 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6026 // eg. forward and remove memory writes of opaque types.
6027 if ((intermediate.getSource() == EShSourceHlsl ||
6028 options->optimizeSize) &&
6029 !options->disableOptimizer) {
6030 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6031
6032 spvtools::Optimizer optimizer(target_env);
6033 optimizer.SetMessageConsumer([](spv_message_level_t level,
6034 const char* source,
6035 const spv_position_t& position,
6036 const char* message) {
6037 std::cerr << StringifyMessage(level, source, position, message)
6038 << std::endl;
6039 });
6040
6041 optimizer.RegisterPass(CreateInlineExhaustivePass());
6042 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6043 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6044 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
6045 optimizer.RegisterPass(CreateInsertExtractElimPass());
6046 optimizer.RegisterPass(CreateAggressiveDCEPass());
6047 optimizer.RegisterPass(CreateDeadBranchElimPass());
6048 optimizer.RegisterPass(CreateBlockMergePass());
6049 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
6050 optimizer.RegisterPass(CreateInsertExtractElimPass());
6051 optimizer.RegisterPass(CreateAggressiveDCEPass());
6052 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6053 // if (options->optimizeSize)
6054 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6055
6056 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6057 return;
6058
6059 // Remove dead module-level objects: functions, types, vars
6060 // TODO(greg-lunarg): Switch to spirv-opt versions when available
6061 spv::spirvbin_t Remapper(0);
6062 Remapper.registerErrorHandler(errHandler);
6063 Remapper.remap(spirv, spv::spirvbin_t::DCE_ALL);
6064 }
6065#endif
6066
John Kessenich140f3df2015-06-26 16:58:36 -06006067 glslang::GetThreadPoolAllocator().pop();
6068}
6069
6070}; // end namespace glslang