blob: b73e538463ca2f8086fee25856dfd4f528b1c41d [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 Kessenichd41993d2017-09-10 15:21:05 -0600161 bool writableParam(glslang::TStorageQualifier);
162 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600163 void makeFunctions(const glslang::TIntermSequence&);
164 void makeGlobalInitializers(const glslang::TIntermSequence&);
165 void visitFunctions(const glslang::TIntermSequence&);
166 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800167 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600168 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
169 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600170 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
171
qining25262b32016-05-06 17:25:16 -0400172 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);
173 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
174 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 +0800175 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 +0800176 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 -0600177 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800178 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 +0800179 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800180 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600181 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 +0800182 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600183 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
184 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700185 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600186 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700187 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400188 spv::Id createSpvConstant(const glslang::TIntermTyped&);
189 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600190 bool isTrivialLeaf(const glslang::TIntermTyped* node);
191 bool isTrivial(const glslang::TIntermTyped* node);
192 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800193 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600194
John Kessenich121853f2017-05-31 17:11:16 -0600195 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600196 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600197 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700198 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600199 int sequenceDepth;
200
Lei Zhang17535f72016-05-04 15:55:59 -0400201 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400202
John Kessenich140f3df2015-06-26 16:58:36 -0600203 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
204 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700205 bool inEntryPoint;
206 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700207 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 -0700208 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600209 const glslang::TIntermediate* glslangIntermediate;
210 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800211 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600212
John Kessenich2f273362015-07-18 22:34:27 -0600213 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600214 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600215 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700216 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600217 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 -0600218 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600219};
220
221//
222// Helper functions for translating glslang representations to SPIR-V enumerants.
223//
224
225// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700226spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600227{
John Kessenich66e2faf2016-03-12 18:34:36 -0700228 switch (source) {
229 case glslang::EShSourceGlsl:
230 switch (profile) {
231 case ENoProfile:
232 case ECoreProfile:
233 case ECompatibilityProfile:
234 return spv::SourceLanguageGLSL;
235 case EEsProfile:
236 return spv::SourceLanguageESSL;
237 default:
238 return spv::SourceLanguageUnknown;
239 }
240 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600241 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600242 default:
243 return spv::SourceLanguageUnknown;
244 }
245}
246
247// Translate glslang language (stage) to SPIR-V execution model.
248spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
249{
250 switch (stage) {
251 case EShLangVertex: return spv::ExecutionModelVertex;
252 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
253 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
254 case EShLangGeometry: return spv::ExecutionModelGeometry;
255 case EShLangFragment: return spv::ExecutionModelFragment;
256 case EShLangCompute: return spv::ExecutionModelGLCompute;
257 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700258 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600259 return spv::ExecutionModelFragment;
260 }
261}
262
John Kessenich140f3df2015-06-26 16:58:36 -0600263// Translate glslang sampler type to SPIR-V dimensionality.
264spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
265{
266 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700267 case glslang::Esd1D: return spv::Dim1D;
268 case glslang::Esd2D: return spv::Dim2D;
269 case glslang::Esd3D: return spv::Dim3D;
270 case glslang::EsdCube: return spv::DimCube;
271 case glslang::EsdRect: return spv::DimRect;
272 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700273 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600274 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700275 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600276 return spv::Dim2D;
277 }
278}
279
John Kessenichf6640762016-08-01 19:44:00 -0600280// Translate glslang precision to SPIR-V precision decorations.
281spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600282{
John Kessenichf6640762016-08-01 19:44:00 -0600283 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700284 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600285 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600286 default:
287 return spv::NoPrecision;
288 }
289}
290
John Kessenichf6640762016-08-01 19:44:00 -0600291// Translate glslang type to SPIR-V precision decorations.
292spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
293{
294 return TranslatePrecisionDecoration(type.getQualifier().precision);
295}
296
John Kessenich140f3df2015-06-26 16:58:36 -0600297// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600298spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600299{
300 if (type.getBasicType() == glslang::EbtBlock) {
301 switch (type.getQualifier().storage) {
302 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600303 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600304 case glslang::EvqVaryingIn: return spv::DecorationBlock;
305 case glslang::EvqVaryingOut: return spv::DecorationBlock;
306 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700307 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600308 break;
309 }
310 }
311
John Kessenich4016e382016-07-15 11:53:56 -0600312 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600313}
314
Rex Xu1da878f2016-02-21 20:59:01 +0800315// Translate glslang type to SPIR-V memory decorations.
316void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
317{
318 if (qualifier.coherent)
319 memory.push_back(spv::DecorationCoherent);
320 if (qualifier.volatil)
321 memory.push_back(spv::DecorationVolatile);
322 if (qualifier.restrict)
323 memory.push_back(spv::DecorationRestrict);
324 if (qualifier.readonly)
325 memory.push_back(spv::DecorationNonWritable);
326 if (qualifier.writeonly)
327 memory.push_back(spv::DecorationNonReadable);
328}
329
John Kessenich140f3df2015-06-26 16:58:36 -0600330// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700331spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600332{
333 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700334 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600335 case glslang::ElmRowMajor:
336 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700337 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600338 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700339 default:
340 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600341 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 }
343 } else {
344 switch (type.getBasicType()) {
345 default:
John Kessenich4016e382016-07-15 11:53:56 -0600346 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600347 break;
348 case glslang::EbtBlock:
349 switch (type.getQualifier().storage) {
350 case glslang::EvqUniform:
351 case glslang::EvqBuffer:
352 switch (type.getQualifier().layoutPacking) {
353 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600354 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
355 default:
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357 }
358 case glslang::EvqVaryingIn:
359 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700360 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600361 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600362 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700363 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600364 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600365 }
366 }
367 }
368}
369
370// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600371// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700372// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800373spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600374{
Rex Xubbceed72016-05-21 09:40:44 +0800375 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700376 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800378 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700379 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700380 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600381 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800382#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800383 else if (qualifier.explicitInterp) {
384 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800385 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800386 }
Rex Xu9d93a232016-05-05 12:30:44 +0800387#endif
Rex Xubbceed72016-05-21 09:40:44 +0800388 else
John Kessenich4016e382016-07-15 11:53:56 -0600389 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800390}
391
392// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600393// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800394// should be applied.
395spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
396{
397 if (qualifier.patch)
398 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700399 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600400 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700401 else if (qualifier.sample) {
402 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600403 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700404 } else
John Kessenich4016e382016-07-15 11:53:56 -0600405 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600406}
407
John Kessenich92187592016-02-01 13:45:25 -0700408// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700409spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600410{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700411 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600412 return spv::DecorationInvariant;
413 else
John Kessenich4016e382016-07-15 11:53:56 -0600414 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600415}
416
qining9220dbb2016-05-04 17:34:38 -0400417// If glslang type is noContraction, return SPIR-V NoContraction decoration.
418spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
419{
420 if (qualifier.noContraction)
421 return spv::DecorationNoContraction;
422 else
John Kessenich4016e382016-07-15 11:53:56 -0600423 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400424}
425
David Netoa901ffe2016-06-08 14:11:40 +0100426// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
427// associated capabilities when required. For some built-in variables, a capability
428// is generated only when using the variable in an executable instruction, but not when
429// just declaring a struct member variable with it. This is true for PointSize,
430// ClipDistance, and CullDistance.
431spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600432{
433 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700434 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600435 // Defer adding the capability until the built-in is actually used.
436 if (! memberDeclaration) {
437 switch (glslangIntermediate->getStage()) {
438 case EShLangGeometry:
439 builder.addCapability(spv::CapabilityGeometryPointSize);
440 break;
441 case EShLangTessControl:
442 case EShLangTessEvaluation:
443 builder.addCapability(spv::CapabilityTessellationPointSize);
444 break;
445 default:
446 break;
447 }
John Kessenich92187592016-02-01 13:45:25 -0700448 }
449 return spv::BuiltInPointSize;
450
John Kessenichebb50532016-05-16 19:22:05 -0600451 // These *Distance capabilities logically belong here, but if the member is declared and
452 // then never used, consumers of SPIR-V prefer the capability not be declared.
453 // They are now generated when used, rather than here when declared.
454 // Potentially, the specification should be more clear what the minimum
455 // use needed is to trigger the capability.
456 //
John Kessenich92187592016-02-01 13:45:25 -0700457 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100458 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800459 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700460 return spv::BuiltInClipDistance;
461
462 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100463 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800464 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700465 return spv::BuiltInCullDistance;
466
467 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600468 builder.addCapability(spv::CapabilityMultiViewport);
469 if (glslangIntermediate->getStage() == EShLangVertex ||
470 glslangIntermediate->getStage() == EShLangTessControl ||
471 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800472
John Kessenichba6a3c22017-09-13 13:22:50 -0600473 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
474 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800475 }
John Kessenich92187592016-02-01 13:45:25 -0700476 return spv::BuiltInViewportIndex;
477
John Kessenich5e801132016-02-15 11:09:46 -0700478 case glslang::EbvSampleId:
479 builder.addCapability(spv::CapabilitySampleRateShading);
480 return spv::BuiltInSampleId;
481
482 case glslang::EbvSamplePosition:
483 builder.addCapability(spv::CapabilitySampleRateShading);
484 return spv::BuiltInSamplePosition;
485
486 case glslang::EbvSampleMask:
487 builder.addCapability(spv::CapabilitySampleRateShading);
488 return spv::BuiltInSampleMask;
489
John Kessenich78a45572016-07-08 14:05:15 -0600490 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600491 builder.addCapability(spv::CapabilityGeometry);
492 if (glslangIntermediate->getStage() == EShLangVertex ||
493 glslangIntermediate->getStage() == EShLangTessControl ||
494 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800495
John Kessenichba6a3c22017-09-13 13:22:50 -0600496 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
497 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800498 }
John Kessenich78a45572016-07-08 14:05:15 -0600499 return spv::BuiltInLayer;
500
John Kessenich140f3df2015-06-26 16:58:36 -0600501 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600502 case glslang::EbvVertexId: return spv::BuiltInVertexId;
503 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700504 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
505 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800506
John Kessenichda581a22015-10-14 14:10:30 -0600507 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800508 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
509 builder.addCapability(spv::CapabilityDrawParameters);
510 return spv::BuiltInBaseVertex;
511
John Kessenichda581a22015-10-14 14:10:30 -0600512 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800513 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
514 builder.addCapability(spv::CapabilityDrawParameters);
515 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200516
John Kessenichda581a22015-10-14 14:10:30 -0600517 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800518 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
519 builder.addCapability(spv::CapabilityDrawParameters);
520 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200521
522 case glslang::EbvPrimitiveId:
523 if (glslangIntermediate->getStage() == EShLangFragment)
524 builder.addCapability(spv::CapabilityGeometry);
525 return spv::BuiltInPrimitiveId;
526
Rex Xu37cdcee2017-06-29 17:46:34 +0800527 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800528 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
529 builder.addCapability(spv::CapabilityStencilExportEXT);
530 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800531
John Kessenich140f3df2015-06-26 16:58:36 -0600532 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600533 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
534 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
535 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
536 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
537 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
538 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
539 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600540 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
541 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
542 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
543 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
544 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
545 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
546 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
547 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800548
Rex Xu574ab042016-04-14 16:53:07 +0800549 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800550 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800551 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
552 return spv::BuiltInSubgroupSize;
553
Rex Xu574ab042016-04-14 16:53:07 +0800554 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800555 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800556 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
557 return spv::BuiltInSubgroupLocalInvocationId;
558
Rex Xu574ab042016-04-14 16:53:07 +0800559 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800560 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
561 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
562 return spv::BuiltInSubgroupEqMaskKHR;
563
Rex Xu574ab042016-04-14 16:53:07 +0800564 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800565 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
566 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
567 return spv::BuiltInSubgroupGeMaskKHR;
568
Rex Xu574ab042016-04-14 16:53:07 +0800569 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800570 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
571 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
572 return spv::BuiltInSubgroupGtMaskKHR;
573
Rex Xu574ab042016-04-14 16:53:07 +0800574 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800575 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
576 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
577 return spv::BuiltInSubgroupLeMaskKHR;
578
Rex Xu574ab042016-04-14 16:53:07 +0800579 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800580 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
581 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
582 return spv::BuiltInSubgroupLtMaskKHR;
583
Rex Xu9d93a232016-05-05 12:30:44 +0800584#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800585 case glslang::EbvBaryCoordNoPersp:
586 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
587 return spv::BuiltInBaryCoordNoPerspAMD;
588
589 case glslang::EbvBaryCoordNoPerspCentroid:
590 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
591 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
592
593 case glslang::EbvBaryCoordNoPerspSample:
594 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
595 return spv::BuiltInBaryCoordNoPerspSampleAMD;
596
597 case glslang::EbvBaryCoordSmooth:
598 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
599 return spv::BuiltInBaryCoordSmoothAMD;
600
601 case glslang::EbvBaryCoordSmoothCentroid:
602 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
603 return spv::BuiltInBaryCoordSmoothCentroidAMD;
604
605 case glslang::EbvBaryCoordSmoothSample:
606 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
607 return spv::BuiltInBaryCoordSmoothSampleAMD;
608
609 case glslang::EbvBaryCoordPullModel:
610 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
611 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800612#endif
chaoc771d89f2017-01-13 01:10:53 -0800613
John Kessenich6c8aaac2017-02-27 01:20:51 -0700614 case glslang::EbvDeviceIndex:
615 builder.addExtension(spv::E_SPV_KHR_device_group);
616 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700617 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700618
619 case glslang::EbvViewIndex:
620 builder.addExtension(spv::E_SPV_KHR_multiview);
621 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700622 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700623
chaoc771d89f2017-01-13 01:10:53 -0800624#ifdef NV_EXTENSIONS
625 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800626 if (!memberDeclaration) {
627 builder.addExtension(spv::E_SPV_NV_viewport_array2);
628 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
629 }
chaoc771d89f2017-01-13 01:10:53 -0800630 return spv::BuiltInViewportMaskNV;
631 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800632 if (!memberDeclaration) {
633 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
634 builder.addCapability(spv::CapabilityShaderStereoViewNV);
635 }
chaoc771d89f2017-01-13 01:10:53 -0800636 return spv::BuiltInSecondaryPositionNV;
637 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800638 if (!memberDeclaration) {
639 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
640 builder.addCapability(spv::CapabilityShaderStereoViewNV);
641 }
chaoc771d89f2017-01-13 01:10:53 -0800642 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800643 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800644 if (!memberDeclaration) {
645 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
646 builder.addCapability(spv::CapabilityPerViewAttributesNV);
647 }
chaocdf3956c2017-02-14 14:52:34 -0800648 return spv::BuiltInPositionPerViewNV;
649 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800650 if (!memberDeclaration) {
651 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
652 builder.addCapability(spv::CapabilityPerViewAttributesNV);
653 }
chaocdf3956c2017-02-14 14:52:34 -0800654 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800655#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800656 default:
657 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600658 }
659}
660
Rex Xufc618912015-09-09 16:42:49 +0800661// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700662spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800663{
664 assert(type.getBasicType() == glslang::EbtSampler);
665
John Kessenich5d0fa972016-02-15 11:57:00 -0700666 // Check for capabilities
667 switch (type.getQualifier().layoutFormat) {
668 case glslang::ElfRg32f:
669 case glslang::ElfRg16f:
670 case glslang::ElfR11fG11fB10f:
671 case glslang::ElfR16f:
672 case glslang::ElfRgba16:
673 case glslang::ElfRgb10A2:
674 case glslang::ElfRg16:
675 case glslang::ElfRg8:
676 case glslang::ElfR16:
677 case glslang::ElfR8:
678 case glslang::ElfRgba16Snorm:
679 case glslang::ElfRg16Snorm:
680 case glslang::ElfRg8Snorm:
681 case glslang::ElfR16Snorm:
682 case glslang::ElfR8Snorm:
683
684 case glslang::ElfRg32i:
685 case glslang::ElfRg16i:
686 case glslang::ElfRg8i:
687 case glslang::ElfR16i:
688 case glslang::ElfR8i:
689
690 case glslang::ElfRgb10a2ui:
691 case glslang::ElfRg32ui:
692 case glslang::ElfRg16ui:
693 case glslang::ElfRg8ui:
694 case glslang::ElfR16ui:
695 case glslang::ElfR8ui:
696 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
697 break;
698
699 default:
700 break;
701 }
702
703 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800704 switch (type.getQualifier().layoutFormat) {
705 case glslang::ElfNone: return spv::ImageFormatUnknown;
706 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
707 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
708 case glslang::ElfR32f: return spv::ImageFormatR32f;
709 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
710 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
711 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
712 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
713 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
714 case glslang::ElfR16f: return spv::ImageFormatR16f;
715 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
716 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
717 case glslang::ElfRg16: return spv::ImageFormatRg16;
718 case glslang::ElfRg8: return spv::ImageFormatRg8;
719 case glslang::ElfR16: return spv::ImageFormatR16;
720 case glslang::ElfR8: return spv::ImageFormatR8;
721 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
722 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
723 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
724 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
725 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
726 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
727 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
728 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
729 case glslang::ElfR32i: return spv::ImageFormatR32i;
730 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
731 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
732 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
733 case glslang::ElfR16i: return spv::ImageFormatR16i;
734 case glslang::ElfR8i: return spv::ImageFormatR8i;
735 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
736 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
737 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
738 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
739 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
740 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
741 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
742 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
743 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
744 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600745 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800746 }
747}
748
Rex Xu57e65922017-07-04 23:23:40 +0800749spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
750{
751 switch (selectionControl) {
752 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
753 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
754 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
755 default: return spv::SelectionControlMaskNone;
756 }
757}
758
steve-lunargf1709e72017-05-02 20:14:50 -0600759spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
760{
761 switch (loopControl) {
762 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
763 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
764 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
765 // TODO: DependencyInfinite
766 // TODO: DependencyLength
767 default: return spv::LoopControlMaskNone;
768 }
769}
770
John Kessenicha5c5fb62017-05-05 05:09:58 -0600771// Translate glslang type to SPIR-V storage class.
772spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
773{
774 if (type.getQualifier().isPipeInput())
775 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600776 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600777 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600778
779 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
780 type.getQualifier().storage == glslang::EvqUniform) {
781 if (type.getBasicType() == glslang::EbtAtomicUint)
782 return spv::StorageClassAtomicCounter;
783 if (type.containsOpaque())
784 return spv::StorageClassUniformConstant;
785 }
786
787 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600788 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
789 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600790 }
791
792 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600793 if (type.getQualifier().layoutPushConstant)
794 return spv::StorageClassPushConstant;
795 if (type.getBasicType() == glslang::EbtBlock)
796 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600797 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600798 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600799
800 switch (type.getQualifier().storage) {
801 case glslang::EvqShared: return spv::StorageClassWorkgroup;
802 case glslang::EvqGlobal: return spv::StorageClassPrivate;
803 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
804 case glslang::EvqTemporary: return spv::StorageClassFunction;
805 default:
806 assert(0);
807 break;
808 }
809
810 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600811}
812
qining25262b32016-05-06 17:25:16 -0400813// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700814// descriptor set.
815bool IsDescriptorResource(const glslang::TType& type)
816{
John Kessenichf7497e22016-03-08 21:36:22 -0700817 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700818 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700819 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700820
821 // non block...
822 // basically samplerXXX/subpass/sampler/texture are all included
823 // if they are the global-scope-class, not the function parameter
824 // (or local, if they ever exist) class.
825 if (type.getBasicType() == glslang::EbtSampler)
826 return type.getQualifier().isUniformOrBuffer();
827
828 // None of the above.
829 return false;
830}
831
John Kesseniche0b6cad2015-12-24 10:30:13 -0700832void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
833{
834 if (child.layoutMatrix == glslang::ElmNone)
835 child.layoutMatrix = parent.layoutMatrix;
836
837 if (parent.invariant)
838 child.invariant = true;
839 if (parent.nopersp)
840 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800841#ifdef AMD_EXTENSIONS
842 if (parent.explicitInterp)
843 child.explicitInterp = true;
844#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700845 if (parent.flat)
846 child.flat = true;
847 if (parent.centroid)
848 child.centroid = true;
849 if (parent.patch)
850 child.patch = true;
851 if (parent.sample)
852 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800853 if (parent.coherent)
854 child.coherent = true;
855 if (parent.volatil)
856 child.volatil = true;
857 if (parent.restrict)
858 child.restrict = true;
859 if (parent.readonly)
860 child.readonly = true;
861 if (parent.writeonly)
862 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700863}
864
John Kessenichf2b7f332016-09-01 17:05:23 -0600865bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700866{
John Kessenich7b9fa252016-01-21 18:56:57 -0700867 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600868 // - struct members might inherit from a struct declaration
869 // (note that non-block structs don't explicitly inherit,
870 // only implicitly, meaning no decoration involved)
871 // - affect decorations on the struct members
872 // (note smooth does not, and expecting something like volatile
873 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700874 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600875 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700876}
877
John Kessenich140f3df2015-06-26 16:58:36 -0600878//
879// Implement the TGlslangToSpvTraverser class.
880//
881
John Kessenich121853f2017-05-31 17:11:16 -0600882TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
883 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
884 : TIntermTraverser(true, false, true),
885 options(options),
886 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600887 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400888 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700889 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600890 glslangIntermediate(glslangIntermediate)
891{
892 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
893
894 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600895 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
896 glslangIntermediate->getVersion());
897
John Kessenich121853f2017-05-31 17:11:16 -0600898 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600899 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600900 builder.setSourceFile(glslangIntermediate->getSourceFile());
901
902 // Set the source shader's text. If for SPV version 1.0, include
903 // a preamble in comments stating the OpModuleProcessed instructions.
904 // Otherwise, emit those as actual instructions.
905 std::string text;
906 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
907 for (int p = 0; p < (int)processes.size(); ++p) {
908 if (glslangIntermediate->getSpv().spv < 0x00010100) {
909 text.append("// OpModuleProcessed ");
910 text.append(processes[p]);
911 text.append("\n");
912 } else
913 builder.addModuleProcessed(processes[p]);
914 }
915 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
916 text.append("#line 1\n");
917 text.append(glslangIntermediate->getSourceText());
918 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600919 }
John Kessenich140f3df2015-06-26 16:58:36 -0600920 stdBuiltins = builder.import("GLSL.std.450");
921 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600922 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
923 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600924
925 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600926 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
927 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600928 builder.addSourceExtension(it->c_str());
929
930 // Add the top-level modes for this shader.
931
John Kessenich92187592016-02-01 13:45:25 -0700932 if (glslangIntermediate->getXfbMode()) {
933 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600934 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700935 }
John Kessenich140f3df2015-06-26 16:58:36 -0600936
937 unsigned int mode;
938 switch (glslangIntermediate->getStage()) {
939 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600940 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600941 break;
942
steve-lunarge7412492017-03-23 11:56:07 -0600943 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600944 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600945 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600946
steve-lunarge7412492017-03-23 11:56:07 -0600947 glslang::TLayoutGeometry primitive;
948
949 if (glslangIntermediate->getStage() == EShLangTessControl) {
950 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
951 primitive = glslangIntermediate->getOutputPrimitive();
952 } else {
953 primitive = glslangIntermediate->getInputPrimitive();
954 }
955
956 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700957 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
958 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
959 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600960 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600961 }
John Kessenich4016e382016-07-15 11:53:56 -0600962 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600963 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
964
John Kesseniche6903322015-10-13 16:29:02 -0600965 switch (glslangIntermediate->getVertexSpacing()) {
966 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
967 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
968 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600969 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600970 }
John Kessenich4016e382016-07-15 11:53:56 -0600971 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600972 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
973
974 switch (glslangIntermediate->getVertexOrder()) {
975 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
976 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600977 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600978 }
John Kessenich4016e382016-07-15 11:53:56 -0600979 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600980 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
981
982 if (glslangIntermediate->getPointMode())
983 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600984 break;
985
986 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600987 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600988 switch (glslangIntermediate->getInputPrimitive()) {
989 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
990 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
991 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700992 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600993 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600994 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600995 }
John Kessenich4016e382016-07-15 11:53:56 -0600996 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600997 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600998
John Kessenich140f3df2015-06-26 16:58:36 -0600999 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1000
1001 switch (glslangIntermediate->getOutputPrimitive()) {
1002 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1003 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1004 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001005 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001006 }
John Kessenich4016e382016-07-15 11:53:56 -06001007 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001008 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1009 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1010 break;
1011
1012 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001013 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001014 if (glslangIntermediate->getPixelCenterInteger())
1015 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001016
John Kessenich140f3df2015-06-26 16:58:36 -06001017 if (glslangIntermediate->getOriginUpperLeft())
1018 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001019 else
1020 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001021
1022 if (glslangIntermediate->getEarlyFragmentTests())
1023 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1024
chaocc1204522017-06-30 17:14:30 -07001025 if (glslangIntermediate->getPostDepthCoverage()) {
1026 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1027 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1028 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1029 }
1030
John Kesseniche6903322015-10-13 16:29:02 -06001031 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001032 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1033 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001034 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001035 }
John Kessenich4016e382016-07-15 11:53:56 -06001036 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001037 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1038
1039 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1040 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001041 break;
1042
1043 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001044 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001045 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1046 glslangIntermediate->getLocalSize(1),
1047 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001048 break;
1049
1050 default:
1051 break;
1052 }
John Kessenich140f3df2015-06-26 16:58:36 -06001053}
1054
John Kessenichfca82622016-11-26 13:23:20 -07001055// Finish creating SPV, after the traversal is complete.
1056void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001057{
John Kessenich517fe7a2016-11-26 13:31:47 -07001058 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001059 builder.setBuildPoint(shaderEntry->getLastBlock());
1060 builder.leaveFunction();
1061 }
1062
John Kessenich7ba63412015-12-20 17:37:07 -07001063 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001064 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1065 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001066
qiningda397332016-03-09 19:54:03 -05001067 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001068}
1069
John Kessenichfca82622016-11-26 13:23:20 -07001070// Write the SPV into 'out'.
1071void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001072{
John Kessenichfca82622016-11-26 13:23:20 -07001073 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001074}
1075
1076//
1077// Implement the traversal functions.
1078//
1079// Return true from interior nodes to have the external traversal
1080// continue on to children. Return false if children were
1081// already processed.
1082//
1083
1084//
qining25262b32016-05-06 17:25:16 -04001085// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001086// - uniform/input reads
1087// - output writes
1088// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1089// - something simple that degenerates into the last bullet
1090//
1091void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1092{
qining75d1d802016-04-06 14:42:01 -04001093 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1094 if (symbol->getType().getQualifier().isSpecConstant())
1095 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1096
John Kessenich140f3df2015-06-26 16:58:36 -06001097 // getSymbolId() will set up all the IO decorations on the first call.
1098 // Formal function parameters were mapped during makeFunctions().
1099 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001100
1101 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1102 if (builder.isPointer(id)) {
1103 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001104 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1105 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1106 iOSet.insert(id);
1107 }
John Kessenich7ba63412015-12-20 17:37:07 -07001108 }
1109
1110 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001111 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001112 // Prepare to generate code for the access
1113
1114 // L-value chains will be computed left to right. We're on the symbol now,
1115 // which is the left-most part of the access chain, so now is "clear" time,
1116 // followed by setting the base.
1117 builder.clearAccessChain();
1118
1119 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001120 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001121 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001122 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001123 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001124 // These are also pure R-values.
1125 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001126 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001127 builder.setAccessChainRValue(id);
1128 else
1129 builder.setAccessChainLValue(id);
1130 }
1131}
1132
1133bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1134{
John Kesseniche485c7a2017-05-31 18:50:53 -06001135 builder.setLine(node->getLoc().line);
1136
qining40887662016-04-03 22:20:42 -04001137 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1138 if (node->getType().getQualifier().isSpecConstant())
1139 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1140
John Kessenich140f3df2015-06-26 16:58:36 -06001141 // First, handle special cases
1142 switch (node->getOp()) {
1143 case glslang::EOpAssign:
1144 case glslang::EOpAddAssign:
1145 case glslang::EOpSubAssign:
1146 case glslang::EOpMulAssign:
1147 case glslang::EOpVectorTimesMatrixAssign:
1148 case glslang::EOpVectorTimesScalarAssign:
1149 case glslang::EOpMatrixTimesScalarAssign:
1150 case glslang::EOpMatrixTimesMatrixAssign:
1151 case glslang::EOpDivAssign:
1152 case glslang::EOpModAssign:
1153 case glslang::EOpAndAssign:
1154 case glslang::EOpInclusiveOrAssign:
1155 case glslang::EOpExclusiveOrAssign:
1156 case glslang::EOpLeftShiftAssign:
1157 case glslang::EOpRightShiftAssign:
1158 // A bin-op assign "a += b" means the same thing as "a = a + b"
1159 // where a is evaluated before b. For a simple assignment, GLSL
1160 // says to evaluate the left before the right. So, always, left
1161 // node then right node.
1162 {
1163 // get the left l-value, save it away
1164 builder.clearAccessChain();
1165 node->getLeft()->traverse(this);
1166 spv::Builder::AccessChain lValue = builder.getAccessChain();
1167
1168 // evaluate the right
1169 builder.clearAccessChain();
1170 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001171 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001172
1173 if (node->getOp() != glslang::EOpAssign) {
1174 // the left is also an r-value
1175 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001176 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001177
1178 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001179 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001180 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001181 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1182 node->getType().getBasicType());
1183
1184 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001185 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001186 }
1187
1188 // store the result
1189 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001190 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001191
1192 // assignments are expressions having an rValue after they are evaluated...
1193 builder.clearAccessChain();
1194 builder.setAccessChainRValue(rValue);
1195 }
1196 return false;
1197 case glslang::EOpIndexDirect:
1198 case glslang::EOpIndexDirectStruct:
1199 {
1200 // Get the left part of the access chain.
1201 node->getLeft()->traverse(this);
1202
1203 // Add the next element in the chain
1204
David Netoa901ffe2016-06-08 14:11:40 +01001205 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001206 if (! node->getLeft()->getType().isArray() &&
1207 node->getLeft()->getType().isVector() &&
1208 node->getOp() == glslang::EOpIndexDirect) {
1209 // This is essentially a hard-coded vector swizzle of size 1,
1210 // so short circuit the access-chain stuff with a swizzle.
1211 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001212 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001213 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001214 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001215 int spvIndex = glslangIndex;
1216 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1217 node->getOp() == glslang::EOpIndexDirectStruct)
1218 {
1219 // This may be, e.g., an anonymous block-member selection, which generally need
1220 // index remapping due to hidden members in anonymous blocks.
1221 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1222 assert(remapper.size() > 0);
1223 spvIndex = remapper[glslangIndex];
1224 }
John Kessenichebb50532016-05-16 19:22:05 -06001225
David Netoa901ffe2016-06-08 14:11:40 +01001226 // normal case for indexing array or structure or block
1227 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1228
1229 // Add capabilities here for accessing PointSize and clip/cull distance.
1230 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001231 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001232 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001233 }
1234 }
1235 return false;
1236 case glslang::EOpIndexIndirect:
1237 {
1238 // Structure or array or vector indirection.
1239 // Will use native SPIR-V access-chain for struct and array indirection;
1240 // matrices are arrays of vectors, so will also work for a matrix.
1241 // Will use the access chain's 'component' for variable index into a vector.
1242
1243 // This adapter is building access chains left to right.
1244 // Set up the access chain to the left.
1245 node->getLeft()->traverse(this);
1246
1247 // save it so that computing the right side doesn't trash it
1248 spv::Builder::AccessChain partial = builder.getAccessChain();
1249
1250 // compute the next index in the chain
1251 builder.clearAccessChain();
1252 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001253 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001254
1255 // restore the saved access chain
1256 builder.setAccessChain(partial);
1257
1258 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001259 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001260 else
John Kessenichfa668da2015-09-13 14:46:30 -06001261 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001262 }
1263 return false;
1264 case glslang::EOpVectorSwizzle:
1265 {
1266 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001267 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001268 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001269 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001270 }
1271 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001272 case glslang::EOpMatrixSwizzle:
1273 logger->missingFunctionality("matrix swizzle");
1274 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001275 case glslang::EOpLogicalOr:
1276 case glslang::EOpLogicalAnd:
1277 {
1278
1279 // These may require short circuiting, but can sometimes be done as straight
1280 // binary operations. The right operand must be short circuited if it has
1281 // side effects, and should probably be if it is complex.
1282 if (isTrivial(node->getRight()->getAsTyped()))
1283 break; // handle below as a normal binary operation
1284 // otherwise, we need to do dynamic short circuiting on the right operand
1285 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1286 builder.clearAccessChain();
1287 builder.setAccessChainRValue(result);
1288 }
1289 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001290 default:
1291 break;
1292 }
1293
1294 // Assume generic binary op...
1295
John Kessenich32cfd492016-02-02 12:37:46 -07001296 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001297 builder.clearAccessChain();
1298 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001299 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001300
John Kessenich32cfd492016-02-02 12:37:46 -07001301 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001302 builder.clearAccessChain();
1303 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001304 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001305
John Kessenich32cfd492016-02-02 12:37:46 -07001306 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001307 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001308 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001309 convertGlslangToSpvType(node->getType()), left, right,
1310 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001311
John Kessenich50e57562015-12-21 21:21:11 -07001312 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001313 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001314 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001315 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001316 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001317 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001318 return false;
1319 }
John Kessenich140f3df2015-06-26 16:58:36 -06001320}
1321
1322bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1323{
John Kesseniche485c7a2017-05-31 18:50:53 -06001324 builder.setLine(node->getLoc().line);
1325
qining40887662016-04-03 22:20:42 -04001326 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1327 if (node->getType().getQualifier().isSpecConstant())
1328 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1329
John Kessenichfc51d282015-08-19 13:34:18 -06001330 spv::Id result = spv::NoResult;
1331
1332 // try texturing first
1333 result = createImageTextureFunctionCall(node);
1334 if (result != spv::NoResult) {
1335 builder.clearAccessChain();
1336 builder.setAccessChainRValue(result);
1337
1338 return false; // done with this node
1339 }
1340
1341 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001342
1343 if (node->getOp() == glslang::EOpArrayLength) {
1344 // Quite special; won't want to evaluate the operand.
1345
1346 // Normal .length() would have been constant folded by the front-end.
1347 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001348 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001349 assert(node->getOperand()->getType().isRuntimeSizedArray());
1350 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1351 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001352 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1353 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001354
1355 builder.clearAccessChain();
1356 builder.setAccessChainRValue(length);
1357
1358 return false;
1359 }
1360
John Kessenichfc51d282015-08-19 13:34:18 -06001361 // Start by evaluating the operand
1362
John Kessenich8c8505c2016-07-26 12:50:38 -06001363 // Does it need a swizzle inversion? If so, evaluation is inverted;
1364 // operate first on the swizzle base, then apply the swizzle.
1365 spv::Id invertedType = spv::NoType;
1366 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1367 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1368 invertedType = getInvertedSwizzleType(*node->getOperand());
1369
John Kessenich140f3df2015-06-26 16:58:36 -06001370 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001371 if (invertedType != spv::NoType)
1372 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1373 else
1374 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001375
Rex Xufc618912015-09-09 16:42:49 +08001376 spv::Id operand = spv::NoResult;
1377
1378 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1379 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001380 node->getOp() == glslang::EOpAtomicCounter ||
1381 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001382 operand = builder.accessChainGetLValue(); // Special case l-value operands
1383 else
John Kessenich32cfd492016-02-02 12:37:46 -07001384 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001385
John Kessenichf6640762016-08-01 19:44:00 -06001386 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001387 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001388
1389 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001390 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001391 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001392
1393 // if not, then possibly an operation
1394 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001395 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001396
1397 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001398 if (invertedType)
1399 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1400
John Kessenich140f3df2015-06-26 16:58:36 -06001401 builder.clearAccessChain();
1402 builder.setAccessChainRValue(result);
1403
1404 return false; // done with this node
1405 }
1406
1407 // it must be a special case, check...
1408 switch (node->getOp()) {
1409 case glslang::EOpPostIncrement:
1410 case glslang::EOpPostDecrement:
1411 case glslang::EOpPreIncrement:
1412 case glslang::EOpPreDecrement:
1413 {
1414 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001415 spv::Id one = 0;
1416 if (node->getBasicType() == glslang::EbtFloat)
1417 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001418 else if (node->getBasicType() == glslang::EbtDouble)
1419 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001420#ifdef AMD_EXTENSIONS
1421 else if (node->getBasicType() == glslang::EbtFloat16)
1422 one = builder.makeFloat16Constant(1.0F);
1423#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001424 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1425 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001426#ifdef AMD_EXTENSIONS
1427 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1428 one = builder.makeInt16Constant(1);
1429#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001430 else
1431 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001432 glslang::TOperator op;
1433 if (node->getOp() == glslang::EOpPreIncrement ||
1434 node->getOp() == glslang::EOpPostIncrement)
1435 op = glslang::EOpAdd;
1436 else
1437 op = glslang::EOpSub;
1438
John Kessenichf6640762016-08-01 19:44:00 -06001439 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001440 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001441 convertGlslangToSpvType(node->getType()), operand, one,
1442 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001443 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001444
1445 // The result of operation is always stored, but conditionally the
1446 // consumed result. The consumed result is always an r-value.
1447 builder.accessChainStore(result);
1448 builder.clearAccessChain();
1449 if (node->getOp() == glslang::EOpPreIncrement ||
1450 node->getOp() == glslang::EOpPreDecrement)
1451 builder.setAccessChainRValue(result);
1452 else
1453 builder.setAccessChainRValue(operand);
1454 }
1455
1456 return false;
1457
1458 case glslang::EOpEmitStreamVertex:
1459 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1460 return false;
1461 case glslang::EOpEndStreamPrimitive:
1462 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1463 return false;
1464
1465 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001466 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001467 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001468 }
John Kessenich140f3df2015-06-26 16:58:36 -06001469}
1470
1471bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1472{
qining27e04a02016-04-14 16:40:20 -04001473 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1474 if (node->getType().getQualifier().isSpecConstant())
1475 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1476
John Kessenichfc51d282015-08-19 13:34:18 -06001477 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001478 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1479 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001480
1481 // try texturing
1482 result = createImageTextureFunctionCall(node);
1483 if (result != spv::NoResult) {
1484 builder.clearAccessChain();
1485 builder.setAccessChainRValue(result);
1486
1487 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001488#ifdef AMD_EXTENSIONS
1489 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1490#else
John Kessenich56bab042015-09-16 10:54:31 -06001491 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001492#endif
Rex Xufc618912015-09-09 16:42:49 +08001493 // "imageStore" is a special case, which has no result
1494 return false;
1495 }
John Kessenichfc51d282015-08-19 13:34:18 -06001496
John Kessenich140f3df2015-06-26 16:58:36 -06001497 glslang::TOperator binOp = glslang::EOpNull;
1498 bool reduceComparison = true;
1499 bool isMatrix = false;
1500 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001501 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001502
1503 assert(node->getOp());
1504
John Kessenichf6640762016-08-01 19:44:00 -06001505 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001506
1507 switch (node->getOp()) {
1508 case glslang::EOpSequence:
1509 {
1510 if (preVisit)
1511 ++sequenceDepth;
1512 else
1513 --sequenceDepth;
1514
1515 if (sequenceDepth == 1) {
1516 // If this is the parent node of all the functions, we want to see them
1517 // early, so all call points have actual SPIR-V functions to reference.
1518 // In all cases, still let the traverser visit the children for us.
1519 makeFunctions(node->getAsAggregate()->getSequence());
1520
John Kessenich6fccb3c2016-09-19 16:01:41 -06001521 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001522 // anything else gets there, so visit out of order, doing them all now.
1523 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1524
John Kessenich6a60c2f2016-12-08 21:01:59 -07001525 // 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 -06001526 // so do them manually.
1527 visitFunctions(node->getAsAggregate()->getSequence());
1528
1529 return false;
1530 }
1531
1532 return true;
1533 }
1534 case glslang::EOpLinkerObjects:
1535 {
1536 if (visit == glslang::EvPreVisit)
1537 linkageOnly = true;
1538 else
1539 linkageOnly = false;
1540
1541 return true;
1542 }
1543 case glslang::EOpComma:
1544 {
1545 // processing from left to right naturally leaves the right-most
1546 // lying around in the access chain
1547 glslang::TIntermSequence& glslangOperands = node->getSequence();
1548 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1549 glslangOperands[i]->traverse(this);
1550
1551 return false;
1552 }
1553 case glslang::EOpFunction:
1554 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001555 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001556 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001557 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001558 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001559 } else {
1560 handleFunctionEntry(node);
1561 }
1562 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001563 if (inEntryPoint)
1564 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001565 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001566 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001567 }
1568
1569 return true;
1570 case glslang::EOpParameters:
1571 // Parameters will have been consumed by EOpFunction processing, but not
1572 // the body, so we still visited the function node's children, making this
1573 // child redundant.
1574 return false;
1575 case glslang::EOpFunctionCall:
1576 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001577 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001578 if (node->isUserDefined())
1579 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001580 // 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 -07001581 if (result) {
1582 builder.clearAccessChain();
1583 builder.setAccessChainRValue(result);
1584 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001585 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001586
1587 return false;
1588 }
1589 case glslang::EOpConstructMat2x2:
1590 case glslang::EOpConstructMat2x3:
1591 case glslang::EOpConstructMat2x4:
1592 case glslang::EOpConstructMat3x2:
1593 case glslang::EOpConstructMat3x3:
1594 case glslang::EOpConstructMat3x4:
1595 case glslang::EOpConstructMat4x2:
1596 case glslang::EOpConstructMat4x3:
1597 case glslang::EOpConstructMat4x4:
1598 case glslang::EOpConstructDMat2x2:
1599 case glslang::EOpConstructDMat2x3:
1600 case glslang::EOpConstructDMat2x4:
1601 case glslang::EOpConstructDMat3x2:
1602 case glslang::EOpConstructDMat3x3:
1603 case glslang::EOpConstructDMat3x4:
1604 case glslang::EOpConstructDMat4x2:
1605 case glslang::EOpConstructDMat4x3:
1606 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001607 case glslang::EOpConstructIMat2x2:
1608 case glslang::EOpConstructIMat2x3:
1609 case glslang::EOpConstructIMat2x4:
1610 case glslang::EOpConstructIMat3x2:
1611 case glslang::EOpConstructIMat3x3:
1612 case glslang::EOpConstructIMat3x4:
1613 case glslang::EOpConstructIMat4x2:
1614 case glslang::EOpConstructIMat4x3:
1615 case glslang::EOpConstructIMat4x4:
1616 case glslang::EOpConstructUMat2x2:
1617 case glslang::EOpConstructUMat2x3:
1618 case glslang::EOpConstructUMat2x4:
1619 case glslang::EOpConstructUMat3x2:
1620 case glslang::EOpConstructUMat3x3:
1621 case glslang::EOpConstructUMat3x4:
1622 case glslang::EOpConstructUMat4x2:
1623 case glslang::EOpConstructUMat4x3:
1624 case glslang::EOpConstructUMat4x4:
1625 case glslang::EOpConstructBMat2x2:
1626 case glslang::EOpConstructBMat2x3:
1627 case glslang::EOpConstructBMat2x4:
1628 case glslang::EOpConstructBMat3x2:
1629 case glslang::EOpConstructBMat3x3:
1630 case glslang::EOpConstructBMat3x4:
1631 case glslang::EOpConstructBMat4x2:
1632 case glslang::EOpConstructBMat4x3:
1633 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001634#ifdef AMD_EXTENSIONS
1635 case glslang::EOpConstructF16Mat2x2:
1636 case glslang::EOpConstructF16Mat2x3:
1637 case glslang::EOpConstructF16Mat2x4:
1638 case glslang::EOpConstructF16Mat3x2:
1639 case glslang::EOpConstructF16Mat3x3:
1640 case glslang::EOpConstructF16Mat3x4:
1641 case glslang::EOpConstructF16Mat4x2:
1642 case glslang::EOpConstructF16Mat4x3:
1643 case glslang::EOpConstructF16Mat4x4:
1644#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001645 isMatrix = true;
1646 // fall through
1647 case glslang::EOpConstructFloat:
1648 case glslang::EOpConstructVec2:
1649 case glslang::EOpConstructVec3:
1650 case glslang::EOpConstructVec4:
1651 case glslang::EOpConstructDouble:
1652 case glslang::EOpConstructDVec2:
1653 case glslang::EOpConstructDVec3:
1654 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001655#ifdef AMD_EXTENSIONS
1656 case glslang::EOpConstructFloat16:
1657 case glslang::EOpConstructF16Vec2:
1658 case glslang::EOpConstructF16Vec3:
1659 case glslang::EOpConstructF16Vec4:
1660#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001661 case glslang::EOpConstructBool:
1662 case glslang::EOpConstructBVec2:
1663 case glslang::EOpConstructBVec3:
1664 case glslang::EOpConstructBVec4:
1665 case glslang::EOpConstructInt:
1666 case glslang::EOpConstructIVec2:
1667 case glslang::EOpConstructIVec3:
1668 case glslang::EOpConstructIVec4:
1669 case glslang::EOpConstructUint:
1670 case glslang::EOpConstructUVec2:
1671 case glslang::EOpConstructUVec3:
1672 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001673 case glslang::EOpConstructInt64:
1674 case glslang::EOpConstructI64Vec2:
1675 case glslang::EOpConstructI64Vec3:
1676 case glslang::EOpConstructI64Vec4:
1677 case glslang::EOpConstructUint64:
1678 case glslang::EOpConstructU64Vec2:
1679 case glslang::EOpConstructU64Vec3:
1680 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001681#ifdef AMD_EXTENSIONS
1682 case glslang::EOpConstructInt16:
1683 case glslang::EOpConstructI16Vec2:
1684 case glslang::EOpConstructI16Vec3:
1685 case glslang::EOpConstructI16Vec4:
1686 case glslang::EOpConstructUint16:
1687 case glslang::EOpConstructU16Vec2:
1688 case glslang::EOpConstructU16Vec3:
1689 case glslang::EOpConstructU16Vec4:
1690#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001691 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001692 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001693 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001694 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001695 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001696 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001697 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001698 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001699 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001700 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001701 std::vector<spv::Id> constituents;
1702 for (int c = 0; c < (int)arguments.size(); ++c)
1703 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001704 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001705 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001706 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001707 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001708 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001709
1710 builder.clearAccessChain();
1711 builder.setAccessChainRValue(constructed);
1712
1713 return false;
1714 }
1715
1716 // These six are component-wise compares with component-wise results.
1717 // Forward on to createBinaryOperation(), requesting a vector result.
1718 case glslang::EOpLessThan:
1719 case glslang::EOpGreaterThan:
1720 case glslang::EOpLessThanEqual:
1721 case glslang::EOpGreaterThanEqual:
1722 case glslang::EOpVectorEqual:
1723 case glslang::EOpVectorNotEqual:
1724 {
1725 // Map the operation to a binary
1726 binOp = node->getOp();
1727 reduceComparison = false;
1728 switch (node->getOp()) {
1729 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1730 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1731 default: binOp = node->getOp(); break;
1732 }
1733
1734 break;
1735 }
1736 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001737 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001738 binOp = glslang::EOpMul;
1739 break;
1740 case glslang::EOpOuterProduct:
1741 // two vectors multiplied to make a matrix
1742 binOp = glslang::EOpOuterProduct;
1743 break;
1744 case glslang::EOpDot:
1745 {
qining25262b32016-05-06 17:25:16 -04001746 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001747 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001748 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001749 binOp = glslang::EOpMul;
1750 break;
1751 }
1752 case glslang::EOpMod:
1753 // when an aggregate, this is the floating-point mod built-in function,
1754 // which can be emitted by the one in createBinaryOperation()
1755 binOp = glslang::EOpMod;
1756 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001757 case glslang::EOpEmitVertex:
1758 case glslang::EOpEndPrimitive:
1759 case glslang::EOpBarrier:
1760 case glslang::EOpMemoryBarrier:
1761 case glslang::EOpMemoryBarrierAtomicCounter:
1762 case glslang::EOpMemoryBarrierBuffer:
1763 case glslang::EOpMemoryBarrierImage:
1764 case glslang::EOpMemoryBarrierShared:
1765 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001766 case glslang::EOpAllMemoryBarrierWithGroupSync:
1767 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1768 case glslang::EOpWorkgroupMemoryBarrier:
1769 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001770 noReturnValue = true;
1771 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1772 break;
1773
John Kessenich426394d2015-07-23 10:22:48 -06001774 case glslang::EOpAtomicAdd:
1775 case glslang::EOpAtomicMin:
1776 case glslang::EOpAtomicMax:
1777 case glslang::EOpAtomicAnd:
1778 case glslang::EOpAtomicOr:
1779 case glslang::EOpAtomicXor:
1780 case glslang::EOpAtomicExchange:
1781 case glslang::EOpAtomicCompSwap:
1782 atomic = true;
1783 break;
1784
John Kessenich0d0c6d32017-07-23 16:08:26 -06001785 case glslang::EOpAtomicCounterAdd:
1786 case glslang::EOpAtomicCounterSubtract:
1787 case glslang::EOpAtomicCounterMin:
1788 case glslang::EOpAtomicCounterMax:
1789 case glslang::EOpAtomicCounterAnd:
1790 case glslang::EOpAtomicCounterOr:
1791 case glslang::EOpAtomicCounterXor:
1792 case glslang::EOpAtomicCounterExchange:
1793 case glslang::EOpAtomicCounterCompSwap:
1794 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1795 builder.addCapability(spv::CapabilityAtomicStorageOps);
1796 atomic = true;
1797 break;
1798
John Kessenich140f3df2015-06-26 16:58:36 -06001799 default:
1800 break;
1801 }
1802
1803 //
1804 // See if it maps to a regular operation.
1805 //
John Kessenich140f3df2015-06-26 16:58:36 -06001806 if (binOp != glslang::EOpNull) {
1807 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1808 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1809 assert(left && right);
1810
1811 builder.clearAccessChain();
1812 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001813 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001814
1815 builder.clearAccessChain();
1816 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001817 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001818
John Kesseniche485c7a2017-05-31 18:50:53 -06001819 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001820 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001821 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001822 left->getType().getBasicType(), reduceComparison);
1823
1824 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001825 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001826 builder.clearAccessChain();
1827 builder.setAccessChainRValue(result);
1828
1829 return false;
1830 }
1831
John Kessenich426394d2015-07-23 10:22:48 -06001832 //
1833 // Create the list of operands.
1834 //
John Kessenich140f3df2015-06-26 16:58:36 -06001835 glslang::TIntermSequence& glslangOperands = node->getSequence();
1836 std::vector<spv::Id> operands;
1837 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001838 // special case l-value operands; there are just a few
1839 bool lvalue = false;
1840 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001841 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001842 case glslang::EOpModf:
1843 if (arg == 1)
1844 lvalue = true;
1845 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001846 case glslang::EOpInterpolateAtSample:
1847 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001848#ifdef AMD_EXTENSIONS
1849 case glslang::EOpInterpolateAtVertex:
1850#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001851 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001852 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001853
1854 // Does it need a swizzle inversion? If so, evaluation is inverted;
1855 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001856 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001857 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1858 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1859 }
Rex Xu7a26c172015-12-08 17:12:09 +08001860 break;
Rex Xud4782c12015-09-06 16:30:11 +08001861 case glslang::EOpAtomicAdd:
1862 case glslang::EOpAtomicMin:
1863 case glslang::EOpAtomicMax:
1864 case glslang::EOpAtomicAnd:
1865 case glslang::EOpAtomicOr:
1866 case glslang::EOpAtomicXor:
1867 case glslang::EOpAtomicExchange:
1868 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001869 case glslang::EOpAtomicCounterAdd:
1870 case glslang::EOpAtomicCounterSubtract:
1871 case glslang::EOpAtomicCounterMin:
1872 case glslang::EOpAtomicCounterMax:
1873 case glslang::EOpAtomicCounterAnd:
1874 case glslang::EOpAtomicCounterOr:
1875 case glslang::EOpAtomicCounterXor:
1876 case glslang::EOpAtomicCounterExchange:
1877 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001878 if (arg == 0)
1879 lvalue = true;
1880 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001881 case glslang::EOpAddCarry:
1882 case glslang::EOpSubBorrow:
1883 if (arg == 2)
1884 lvalue = true;
1885 break;
1886 case glslang::EOpUMulExtended:
1887 case glslang::EOpIMulExtended:
1888 if (arg >= 2)
1889 lvalue = true;
1890 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001891 default:
1892 break;
1893 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001894 builder.clearAccessChain();
1895 if (invertedType != spv::NoType && arg == 0)
1896 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1897 else
1898 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001899 if (lvalue)
1900 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001901 else {
1902 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001903 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001904 }
John Kessenich140f3df2015-06-26 16:58:36 -06001905 }
John Kessenich426394d2015-07-23 10:22:48 -06001906
John Kesseniche485c7a2017-05-31 18:50:53 -06001907 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001908 if (atomic) {
1909 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001910 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001911 } else {
1912 // Pass through to generic operations.
1913 switch (glslangOperands.size()) {
1914 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001915 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001916 break;
1917 case 1:
qining25262b32016-05-06 17:25:16 -04001918 result = createUnaryOperation(
1919 node->getOp(), precision,
1920 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001921 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001922 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001923 break;
1924 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001925 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001926 break;
1927 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001928 if (invertedType)
1929 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001930 }
1931
1932 if (noReturnValue)
1933 return false;
1934
1935 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001936 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001937 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001938 } else {
1939 builder.clearAccessChain();
1940 builder.setAccessChainRValue(result);
1941 return false;
1942 }
1943}
1944
John Kessenich433e9ff2017-01-26 20:31:11 -07001945// This path handles both if-then-else and ?:
1946// The if-then-else has a node type of void, while
1947// ?: has either a void or a non-void node type
1948//
1949// Leaving the result, when not void:
1950// GLSL only has r-values as the result of a :?, but
1951// if we have an l-value, that can be more efficient if it will
1952// become the base of a complex r-value expression, because the
1953// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001954bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1955{
John Kessenich433e9ff2017-01-26 20:31:11 -07001956 // See if it simple and safe to generate OpSelect instead of using control flow.
1957 // Crucially, side effects must be avoided, and there are performance trade-offs.
1958 // Return true if good idea (and safe) for OpSelect, false otherwise.
1959 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001960 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1961 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001962 return false;
1963
1964 if (node->getTrueBlock() == nullptr ||
1965 node->getFalseBlock() == nullptr)
1966 return false;
1967
1968 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1969 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1970
1971 // return true if a single operand to ? : is okay for OpSelect
1972 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001973 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001974 };
1975
1976 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1977 operandOkay(node->getFalseBlock()->getAsTyped());
1978 };
1979
1980 // Emit OpSelect for this selection.
1981 const auto handleAsOpSelect = [&]() {
1982 node->getCondition()->traverse(this);
1983 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1984 node->getTrueBlock()->traverse(this);
1985 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1986 node->getFalseBlock()->traverse(this);
1987 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1988
John Kesseniche485c7a2017-05-31 18:50:53 -06001989 builder.setLine(node->getLoc().line);
1990
John Kesseniche434ad92017-03-30 10:09:28 -06001991 // smear condition to vector, if necessary (AST is always scalar)
1992 if (builder.isVector(trueValue))
1993 condition = builder.smearScalar(spv::NoPrecision, condition,
1994 builder.makeVectorType(builder.makeBoolType(),
1995 builder.getNumComponents(trueValue)));
1996
1997 spv::Id select = builder.createTriOp(spv::OpSelect,
1998 convertGlslangToSpvType(node->getType()), condition,
1999 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07002000 builder.clearAccessChain();
2001 builder.setAccessChainRValue(select);
2002 };
2003
2004 // Try for OpSelect
2005
2006 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002007 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2008 if (node->getType().getQualifier().isSpecConstant())
2009 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2010
John Kessenich433e9ff2017-01-26 20:31:11 -07002011 handleAsOpSelect();
2012 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002013 }
2014
Rex Xu57e65922017-07-04 23:23:40 +08002015 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07002016 // Don't handle results as temporaries, because there will be two names
2017 // and better to leave SSA to later passes.
2018 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
2019 ? spv::NoResult
2020 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2021
John Kessenich140f3df2015-06-26 16:58:36 -06002022 // emit the condition before doing anything with selection
2023 node->getCondition()->traverse(this);
2024
Rex Xu57e65922017-07-04 23:23:40 +08002025 // Selection control:
2026 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2027
John Kessenich140f3df2015-06-26 16:58:36 -06002028 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08002029 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06002030
John Kessenich433e9ff2017-01-26 20:31:11 -07002031 // emit the "then" statement
2032 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002033 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002034 if (result != spv::NoResult)
2035 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002036 }
2037
John Kessenich433e9ff2017-01-26 20:31:11 -07002038 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002039 ifBuilder.makeBeginElse();
2040 // emit the "else" statement
2041 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002042 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002043 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002044 }
2045
John Kessenich433e9ff2017-01-26 20:31:11 -07002046 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002047 ifBuilder.makeEndIf();
2048
John Kessenich433e9ff2017-01-26 20:31:11 -07002049 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002050 // GLSL only has r-values as the result of a :?, but
2051 // if we have an l-value, that can be more efficient if it will
2052 // become the base of a complex r-value expression, because the
2053 // next layer copies r-values into memory to use the access-chain mechanism
2054 builder.clearAccessChain();
2055 builder.setAccessChainLValue(result);
2056 }
2057
2058 return false;
2059}
2060
2061bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2062{
2063 // emit and get the condition before doing anything with switch
2064 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002065 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002066
Rex Xu57e65922017-07-04 23:23:40 +08002067 // Selection control:
2068 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2069
John Kessenich140f3df2015-06-26 16:58:36 -06002070 // browse the children to sort out code segments
2071 int defaultSegment = -1;
2072 std::vector<TIntermNode*> codeSegments;
2073 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2074 std::vector<int> caseValues;
2075 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2076 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2077 TIntermNode* child = *c;
2078 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002079 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002080 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002081 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002082 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2083 } else
2084 codeSegments.push_back(child);
2085 }
2086
qining25262b32016-05-06 17:25:16 -04002087 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002088 // statements between the last case and the end of the switch statement
2089 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2090 (int)codeSegments.size() == defaultSegment)
2091 codeSegments.push_back(nullptr);
2092
2093 // make the switch statement
2094 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002095 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002096
2097 // emit all the code in the segments
2098 breakForLoop.push(false);
2099 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2100 builder.nextSwitchSegment(segmentBlocks, s);
2101 if (codeSegments[s])
2102 codeSegments[s]->traverse(this);
2103 else
2104 builder.addSwitchBreak();
2105 }
2106 breakForLoop.pop();
2107
2108 builder.endSwitch(segmentBlocks);
2109
2110 return false;
2111}
2112
2113void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2114{
2115 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002116 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002117
2118 builder.clearAccessChain();
2119 builder.setAccessChainRValue(constant);
2120}
2121
2122bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2123{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002124 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002125 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002126
2127 // Loop control:
2128 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2129
2130 // TODO: dependency length
2131
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002132 // Spec requires back edges to target header blocks, and every header block
2133 // must dominate its merge block. Make a header block first to ensure these
2134 // conditions are met. By definition, it will contain OpLoopMerge, followed
2135 // by a block-ending branch. But we don't want to put any other body/test
2136 // instructions in it, since the body/test may have arbitrary instructions,
2137 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002138 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002139 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002140 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002141 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002142 spv::Block& test = builder.makeNewBlock();
2143 builder.createBranch(&test);
2144
2145 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002146 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002147 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002148 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2149
2150 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002151 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002152 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002153 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002154 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002155 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002156
2157 builder.setBuildPoint(&blocks.continue_target);
2158 if (node->getTerminal())
2159 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002160 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002161 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002162 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002163 builder.createBranch(&blocks.body);
2164
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002165 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002166 builder.setBuildPoint(&blocks.body);
2167 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002168 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002169 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002170 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002171
2172 builder.setBuildPoint(&blocks.continue_target);
2173 if (node->getTerminal())
2174 node->getTerminal()->traverse(this);
2175 if (node->getTest()) {
2176 node->getTest()->traverse(this);
2177 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002178 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002179 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002180 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002181 // TODO: unless there was a break/return/discard instruction
2182 // somewhere in the body, this is an infinite loop, so we should
2183 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002184 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002185 }
John Kessenich140f3df2015-06-26 16:58:36 -06002186 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002187 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002188 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002189 return false;
2190}
2191
2192bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2193{
2194 if (node->getExpression())
2195 node->getExpression()->traverse(this);
2196
John Kesseniche485c7a2017-05-31 18:50:53 -06002197 builder.setLine(node->getLoc().line);
2198
John Kessenich140f3df2015-06-26 16:58:36 -06002199 switch (node->getFlowOp()) {
2200 case glslang::EOpKill:
2201 builder.makeDiscard();
2202 break;
2203 case glslang::EOpBreak:
2204 if (breakForLoop.top())
2205 builder.createLoopExit();
2206 else
2207 builder.addSwitchBreak();
2208 break;
2209 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002210 builder.createLoopContinue();
2211 break;
2212 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002213 if (node->getExpression()) {
2214 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2215 spv::Id returnId = accessChainLoad(glslangReturnType);
2216 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2217 builder.clearAccessChain();
2218 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2219 builder.setAccessChainLValue(copyId);
2220 multiTypeStore(glslangReturnType, returnId);
2221 returnId = builder.createLoad(copyId);
2222 }
2223 builder.makeReturn(false, returnId);
2224 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002225 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002226
2227 builder.clearAccessChain();
2228 break;
2229
2230 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002231 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002232 break;
2233 }
2234
2235 return false;
2236}
2237
2238spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2239{
qining25262b32016-05-06 17:25:16 -04002240 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002241 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002242 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002243 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002244 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002245 }
2246
2247 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002248 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002249 spv::Id spvType = convertGlslangToSpvType(node->getType());
2250
Rex Xuf89ad982017-04-07 23:22:33 +08002251#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002252 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2253 node->getType().containsBasicType(glslang::EbtInt16) ||
2254 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002255 if (contains16BitType) {
2256 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2257 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2258 builder.addCapability(spv::CapabilityStorageInputOutput16);
2259 } else if (storageClass == spv::StorageClassPushConstant) {
2260 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2261 builder.addCapability(spv::CapabilityStoragePushConstant16);
2262 } else if (storageClass == spv::StorageClassUniform) {
2263 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2264 builder.addCapability(spv::CapabilityStorageUniform16);
2265 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2266 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2267 }
2268 }
2269#endif
2270
John Kessenich140f3df2015-06-26 16:58:36 -06002271 const char* name = node->getName().c_str();
2272 if (glslang::IsAnonymous(name))
2273 name = "";
2274
2275 return builder.createVariable(storageClass, spvType, name);
2276}
2277
2278// Return type Id of the sampled type.
2279spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2280{
2281 switch (sampler.type) {
2282 case glslang::EbtFloat: return builder.makeFloatType(32);
2283 case glslang::EbtInt: return builder.makeIntType(32);
2284 case glslang::EbtUint: return builder.makeUintType(32);
2285 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002286 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002287 return builder.makeFloatType(32);
2288 }
2289}
2290
John Kessenich8c8505c2016-07-26 12:50:38 -06002291// If node is a swizzle operation, return the type that should be used if
2292// the swizzle base is first consumed by another operation, before the swizzle
2293// is applied.
2294spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2295{
John Kessenichecba76f2017-01-06 00:34:48 -07002296 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002297 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2298 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2299 else
2300 return spv::NoType;
2301}
2302
2303// When inverting a swizzle with a parent op, this function
2304// will apply the swizzle operation to a completed parent operation.
2305spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2306{
2307 std::vector<unsigned> swizzle;
2308 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2309 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2310}
2311
John Kessenich8c8505c2016-07-26 12:50:38 -06002312// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2313void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2314{
2315 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2316 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2317 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2318}
2319
John Kessenich3ac051e2015-12-20 11:29:16 -07002320// Convert from a glslang type to an SPV type, by calling into a
2321// recursive version of this function. This establishes the inherited
2322// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002323spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2324{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002325 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002326}
2327
2328// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002329// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002330// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002331spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002332{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002333 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002334
2335 switch (type.getBasicType()) {
2336 case glslang::EbtVoid:
2337 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002338 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002339 break;
2340 case glslang::EbtFloat:
2341 spvType = builder.makeFloatType(32);
2342 break;
2343 case glslang::EbtDouble:
2344 spvType = builder.makeFloatType(64);
2345 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002346#ifdef AMD_EXTENSIONS
2347 case glslang::EbtFloat16:
2348 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002349 spvType = builder.makeFloatType(16);
2350 break;
2351#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002352 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002353 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2354 // a 32-bit int where non-0 means true.
2355 if (explicitLayout != glslang::ElpNone)
2356 spvType = builder.makeUintType(32);
2357 else
2358 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002359 break;
2360 case glslang::EbtInt:
2361 spvType = builder.makeIntType(32);
2362 break;
2363 case glslang::EbtUint:
2364 spvType = builder.makeUintType(32);
2365 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002366 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002367 spvType = builder.makeIntType(64);
2368 break;
2369 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002370 spvType = builder.makeUintType(64);
2371 break;
Rex Xucabbb782017-03-24 13:41:14 +08002372#ifdef AMD_EXTENSIONS
2373 case glslang::EbtInt16:
2374 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2375 spvType = builder.makeIntType(16);
2376 break;
2377 case glslang::EbtUint16:
2378 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2379 spvType = builder.makeUintType(16);
2380 break;
2381#endif
John Kessenich426394d2015-07-23 10:22:48 -06002382 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002383 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002384 spvType = builder.makeUintType(32);
2385 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002386 case glslang::EbtSampler:
2387 {
2388 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002389 if (sampler.sampler) {
2390 // pure sampler
2391 spvType = builder.makeSamplerType();
2392 } else {
2393 // an image is present, make its type
2394 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2395 sampler.image ? 2 : 1, TranslateImageFormat(type));
2396 if (sampler.combined) {
2397 // already has both image and sampler, make the combined type
2398 spvType = builder.makeSampledImageType(spvType);
2399 }
John Kessenich55e7d112015-11-15 21:33:39 -07002400 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002401 }
John Kessenich140f3df2015-06-26 16:58:36 -06002402 break;
2403 case glslang::EbtStruct:
2404 case glslang::EbtBlock:
2405 {
2406 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002407 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002408
2409 // Try to share structs for different layouts, but not yet for other
2410 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002411 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002412 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002413 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002414 break;
2415
2416 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002417 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002418 memberRemapper[glslangMembers].resize(glslangMembers->size());
2419 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002420 }
2421 break;
2422 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002423 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002424 break;
2425 }
2426
2427 if (type.isMatrix())
2428 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2429 else {
2430 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2431 if (type.getVectorSize() > 1)
2432 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2433 }
2434
2435 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002436 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2437
John Kessenichc9a80832015-09-12 12:17:44 -06002438 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002439 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002440 // We need to decorate array strides for types needing explicit layout, except blocks.
2441 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002442 // Use a dummy glslang type for querying internal strides of
2443 // arrays of arrays, but using just a one-dimensional array.
2444 glslang::TType simpleArrayType(type, 0); // deference type of the array
2445 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2446 simpleArrayType.getArraySizes().dereference();
2447
2448 // Will compute the higher-order strides here, rather than making a whole
2449 // pile of types and doing repetitive recursion on their contents.
2450 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2451 }
John Kessenichf8842e52016-01-04 19:22:56 -07002452
2453 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002454 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002455 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002456 if (stride > 0)
2457 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002458 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002459 }
2460 } else {
2461 // single-dimensional array, and don't yet have stride
2462
John Kessenichf8842e52016-01-04 19:22:56 -07002463 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002464 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2465 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002466 }
John Kessenich31ed4832015-09-09 17:51:38 -06002467
John Kessenichc9a80832015-09-12 12:17:44 -06002468 // Do the outer dimension, which might not be known for a runtime-sized array
2469 if (type.isRuntimeSizedArray()) {
2470 spvType = builder.makeRuntimeArray(spvType);
2471 } else {
2472 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002473 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002474 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002475 if (stride > 0)
2476 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002477 }
2478
2479 return spvType;
2480}
2481
John Kessenich0e737842017-03-24 18:38:16 -06002482// TODO: this functionality should exist at a higher level, in creating the AST
2483//
2484// Identify interface members that don't have their required extension turned on.
2485//
2486bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2487{
2488 auto& extensions = glslangIntermediate->getRequestedExtensions();
2489
Rex Xubcf291a2017-03-29 23:01:36 +08002490 if (member.getFieldName() == "gl_ViewportMask" &&
2491 extensions.find("GL_NV_viewport_array2") == extensions.end())
2492 return true;
2493 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2494 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2495 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002496 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2497 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2498 return true;
2499 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2500 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2501 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002502 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2503 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2504 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002505
2506 return false;
2507};
2508
John Kessenich6090df02016-06-30 21:18:02 -06002509// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2510// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2511// Mutually recursive with convertGlslangToSpvType().
2512spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2513 const glslang::TTypeList* glslangMembers,
2514 glslang::TLayoutPacking explicitLayout,
2515 const glslang::TQualifier& qualifier)
2516{
2517 // Create a vector of struct types for SPIR-V to consume
2518 std::vector<spv::Id> spvMembers;
2519 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 -06002520 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2521 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2522 if (glslangMember.hiddenMember()) {
2523 ++memberDelta;
2524 if (type.getBasicType() == glslang::EbtBlock)
2525 memberRemapper[glslangMembers][i] = -1;
2526 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002527 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002528 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002529 if (filterMember(glslangMember))
2530 continue;
2531 }
John Kessenich6090df02016-06-30 21:18:02 -06002532 // modify just this child's view of the qualifier
2533 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2534 InheritQualifiers(memberQualifier, qualifier);
2535
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002536 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002537 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002538 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002539
2540 // recurse
2541 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2542 }
2543 }
2544
2545 // Make the SPIR-V type
2546 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002547 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002548 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2549
2550 // Decorate it
2551 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2552
2553 return spvType;
2554}
2555
2556void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2557 const glslang::TTypeList* glslangMembers,
2558 glslang::TLayoutPacking explicitLayout,
2559 const glslang::TQualifier& qualifier,
2560 spv::Id spvType)
2561{
2562 // Name and decorate the non-hidden members
2563 int offset = -1;
2564 int locationOffset = 0; // for use within the members of this struct
2565 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2566 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2567 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002568 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002569 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002570 if (filterMember(glslangMember))
2571 continue;
2572 }
John Kessenich6090df02016-06-30 21:18:02 -06002573
2574 // modify just this child's view of the qualifier
2575 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2576 InheritQualifiers(memberQualifier, qualifier);
2577
2578 // using -1 above to indicate a hidden member
2579 if (member >= 0) {
2580 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2581 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2582 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2583 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002584 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2585 type.getQualifier().storage == glslang::EvqVaryingOut) {
2586 if (type.getBasicType() == glslang::EbtBlock ||
2587 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002588 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2589 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2590 }
2591 }
2592 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2593
Rex Xu286ca432017-07-27 14:33:16 +08002594 if (type.getBasicType() == glslang::EbtBlock &&
2595 qualifier.storage == glslang::EvqBuffer) {
2596 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002597 std::vector<spv::Decoration> memory;
2598 TranslateMemoryDecoration(memberQualifier, memory);
2599 for (unsigned int i = 0; i < memory.size(); ++i)
2600 addMemberDecoration(spvType, member, memory[i]);
2601 }
2602
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002603 // Location assignment was already completed correctly by the front end,
2604 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002605 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002606 // ill-specified and decisions have been made to not allow this.
2607 if (! type.isArray() && memberQualifier.hasLocation())
2608 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002609
John Kessenich2f47bc92016-06-30 21:47:35 -06002610 if (qualifier.hasLocation()) // track for upcoming inheritance
2611 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2612
John Kessenich6090df02016-06-30 21:18:02 -06002613 // component, XFB, others
2614 if (glslangMember.getQualifier().hasComponent())
2615 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2616 if (glslangMember.getQualifier().hasXfbOffset())
2617 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2618 else if (explicitLayout != glslang::ElpNone) {
2619 // figure out what to do with offset, which is accumulating
2620 int nextOffset;
2621 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2622 if (offset >= 0)
2623 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2624 offset = nextOffset;
2625 }
2626
2627 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2628 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2629
2630 // built-in variable decorations
2631 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002632 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002633 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002634
2635#ifdef NV_EXTENSIONS
2636 if (builtIn == spv::BuiltInLayer) {
2637 // SPV_NV_viewport_array2 extension
2638 if (glslangMember.getQualifier().layoutViewportRelative){
2639 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2640 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2641 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2642 }
2643 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2644 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2645 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2646 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2647 }
2648 }
chaocdf3956c2017-02-14 14:52:34 -08002649 if (glslangMember.getQualifier().layoutPassthrough) {
2650 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2651 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2652 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2653 }
chaoc771d89f2017-01-13 01:10:53 -08002654#endif
John Kessenich6090df02016-06-30 21:18:02 -06002655 }
2656 }
2657
2658 // Decorate the structure
2659 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002660 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002661 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2662 builder.addCapability(spv::CapabilityGeometryStreams);
2663 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2664 }
2665 if (glslangIntermediate->getXfbMode()) {
2666 builder.addCapability(spv::CapabilityTransformFeedback);
2667 if (type.getQualifier().hasXfbStride())
2668 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2669 if (type.getQualifier().hasXfbBuffer())
2670 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2671 }
2672}
2673
John Kessenich6c292d32016-02-15 20:58:50 -07002674// Turn the expression forming the array size into an id.
2675// This is not quite trivial, because of specialization constants.
2676// Sometimes, a raw constant is turned into an Id, and sometimes
2677// a specialization constant expression is.
2678spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2679{
2680 // First, see if this is sized with a node, meaning a specialization constant:
2681 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2682 if (specNode != nullptr) {
2683 builder.clearAccessChain();
2684 specNode->traverse(this);
2685 return accessChainLoad(specNode->getAsTyped()->getType());
2686 }
qining25262b32016-05-06 17:25:16 -04002687
John Kessenich6c292d32016-02-15 20:58:50 -07002688 // Otherwise, need a compile-time (front end) size, get it:
2689 int size = arraySizes.getDimSize(dim);
2690 assert(size > 0);
2691 return builder.makeUintConstant(size);
2692}
2693
John Kessenich103bef92016-02-08 21:38:15 -07002694// Wrap the builder's accessChainLoad to:
2695// - localize handling of RelaxedPrecision
2696// - use the SPIR-V inferred type instead of another conversion of the glslang type
2697// (avoids unnecessary work and possible type punning for structures)
2698// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002699spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2700{
John Kessenich103bef92016-02-08 21:38:15 -07002701 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2702 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2703
2704 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002705 if (type.getBasicType() == glslang::EbtBool) {
2706 if (builder.isScalarType(nominalTypeId)) {
2707 // Conversion for bool
2708 spv::Id boolType = builder.makeBoolType();
2709 if (nominalTypeId != boolType)
2710 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2711 } else if (builder.isVectorType(nominalTypeId)) {
2712 // Conversion for bvec
2713 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2714 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2715 if (nominalTypeId != bvecType)
2716 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2717 }
2718 }
John Kessenich103bef92016-02-08 21:38:15 -07002719
2720 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002721}
2722
Rex Xu27253232016-02-23 17:51:09 +08002723// Wrap the builder's accessChainStore to:
2724// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002725//
2726// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002727void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2728{
2729 // Need to convert to abstract types when necessary
2730 if (type.getBasicType() == glslang::EbtBool) {
2731 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2732
2733 if (builder.isScalarType(nominalTypeId)) {
2734 // Conversion for bool
2735 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002736 if (nominalTypeId != boolType) {
2737 // keep these outside arguments, for determinant order-of-evaluation
2738 spv::Id one = builder.makeUintConstant(1);
2739 spv::Id zero = builder.makeUintConstant(0);
2740 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2741 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002742 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002743 } else if (builder.isVectorType(nominalTypeId)) {
2744 // Conversion for bvec
2745 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2746 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002747 if (nominalTypeId != bvecType) {
2748 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002749 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2750 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2751 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002752 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002753 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2754 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002755 }
2756 }
2757
2758 builder.accessChainStore(rvalue);
2759}
2760
John Kessenich4bf71552016-09-02 11:20:21 -06002761// For storing when types match at the glslang level, but not might match at the
2762// SPIR-V level.
2763//
2764// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002765// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002766// as in a member-decorated way.
2767//
2768// NOTE: This function can handle any store request; if it's not special it
2769// simplifies to a simple OpStore.
2770//
2771// Implicitly uses the existing builder.accessChain as the storage target.
2772void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2773{
John Kessenichb3e24e42016-09-11 12:33:43 -06002774 // we only do the complex path here if it's an aggregate
2775 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002776 accessChainStore(type, rValue);
2777 return;
2778 }
2779
John Kessenichb3e24e42016-09-11 12:33:43 -06002780 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002781 spv::Id rType = builder.getTypeId(rValue);
2782 spv::Id lValue = builder.accessChainGetLValue();
2783 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2784 if (lType == rType) {
2785 accessChainStore(type, rValue);
2786 return;
2787 }
2788
John Kessenichb3e24e42016-09-11 12:33:43 -06002789 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002790 // where the two types were the same type in GLSL. This requires member
2791 // by member copy, recursively.
2792
John Kessenichb3e24e42016-09-11 12:33:43 -06002793 // If an array, copy element by element.
2794 if (type.isArray()) {
2795 glslang::TType glslangElementType(type, 0);
2796 spv::Id elementRType = builder.getContainedTypeId(rType);
2797 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2798 // get the source member
2799 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002800
John Kessenichb3e24e42016-09-11 12:33:43 -06002801 // set up the target storage
2802 builder.clearAccessChain();
2803 builder.setAccessChainLValue(lValue);
2804 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002805
John Kessenichb3e24e42016-09-11 12:33:43 -06002806 // store the member
2807 multiTypeStore(glslangElementType, elementRValue);
2808 }
2809 } else {
2810 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002811
John Kessenichb3e24e42016-09-11 12:33:43 -06002812 // loop over structure members
2813 const glslang::TTypeList& members = *type.getStruct();
2814 for (int m = 0; m < (int)members.size(); ++m) {
2815 const glslang::TType& glslangMemberType = *members[m].type;
2816
2817 // get the source member
2818 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2819 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2820
2821 // set up the target storage
2822 builder.clearAccessChain();
2823 builder.setAccessChainLValue(lValue);
2824 builder.accessChainPush(builder.makeIntConstant(m));
2825
2826 // store the member
2827 multiTypeStore(glslangMemberType, memberRValue);
2828 }
John Kessenich4bf71552016-09-02 11:20:21 -06002829 }
2830}
2831
John Kessenichf85e8062015-12-19 13:57:10 -07002832// Decide whether or not this type should be
2833// decorated with offsets and strides, and if so
2834// whether std140 or std430 rules should be applied.
2835glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002836{
John Kessenichf85e8062015-12-19 13:57:10 -07002837 // has to be a block
2838 if (type.getBasicType() != glslang::EbtBlock)
2839 return glslang::ElpNone;
2840
2841 // has to be a uniform or buffer block
2842 if (type.getQualifier().storage != glslang::EvqUniform &&
2843 type.getQualifier().storage != glslang::EvqBuffer)
2844 return glslang::ElpNone;
2845
2846 // return the layout to use
2847 switch (type.getQualifier().layoutPacking) {
2848 case glslang::ElpStd140:
2849 case glslang::ElpStd430:
2850 return type.getQualifier().layoutPacking;
2851 default:
2852 return glslang::ElpNone;
2853 }
John Kessenich31ed4832015-09-09 17:51:38 -06002854}
2855
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002856// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002857int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002858{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002859 int size;
John Kessenich49987892015-12-29 17:11:44 -07002860 int stride;
2861 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002862
2863 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002864}
2865
John Kessenich49987892015-12-29 17:11:44 -07002866// 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 -07002867// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002868int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002869{
John Kessenich49987892015-12-29 17:11:44 -07002870 glslang::TType elementType;
2871 elementType.shallowCopy(matrixType);
2872 elementType.clearArraySizes();
2873
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002874 int size;
John Kessenich49987892015-12-29 17:11:44 -07002875 int stride;
2876 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2877
2878 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002879}
2880
John Kessenich5e4b1242015-08-06 22:53:06 -06002881// Given a member type of a struct, realign the current offset for it, and compute
2882// the next (not yet aligned) offset for the next member, which will get aligned
2883// on the next call.
2884// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2885// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2886// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002887void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002888 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002889{
2890 // this will get a positive value when deemed necessary
2891 nextOffset = -1;
2892
John Kessenich5e4b1242015-08-06 22:53:06 -06002893 // override anything in currentOffset with user-set offset
2894 if (memberType.getQualifier().hasOffset())
2895 currentOffset = memberType.getQualifier().layoutOffset;
2896
2897 // It could be that current linker usage in glslang updated all the layoutOffset,
2898 // in which case the following code does not matter. But, that's not quite right
2899 // once cross-compilation unit GLSL validation is done, as the original user
2900 // settings are needed in layoutOffset, and then the following will come into play.
2901
John Kessenichf85e8062015-12-19 13:57:10 -07002902 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002903 if (! memberType.getQualifier().hasOffset())
2904 currentOffset = -1;
2905
2906 return;
2907 }
2908
John Kessenichf85e8062015-12-19 13:57:10 -07002909 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002910 if (currentOffset < 0)
2911 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002912
John Kessenich5e4b1242015-08-06 22:53:06 -06002913 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2914 // but possibly not yet correctly aligned.
2915
2916 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002917 int dummyStride;
2918 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002919
2920 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002921 // TODO: make this consistent in early phases of code:
2922 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2923 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2924 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002925 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002926 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002927 int dummySize;
2928 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2929 if (componentAlignment <= 4)
2930 memberAlignment = componentAlignment;
2931 }
2932
2933 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002934 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002935
2936 // Bump up to vec4 if there is a bad straddle
2937 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2938 glslang::RoundToPow2(currentOffset, 16);
2939
John Kessenich5e4b1242015-08-06 22:53:06 -06002940 nextOffset = currentOffset + memberSize;
2941}
2942
David Netoa901ffe2016-06-08 14:11:40 +01002943void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002944{
David Netoa901ffe2016-06-08 14:11:40 +01002945 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2946 switch (glslangBuiltIn)
2947 {
2948 case glslang::EbvClipDistance:
2949 case glslang::EbvCullDistance:
2950 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002951#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08002952 case glslang::EbvViewportMaskNV:
2953 case glslang::EbvSecondaryPositionNV:
2954 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002955 case glslang::EbvPositionPerViewNV:
2956 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002957#endif
David Netoa901ffe2016-06-08 14:11:40 +01002958 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2959 // Alternately, we could just call this for any glslang built-in, since the
2960 // capability already guards against duplicates.
2961 TranslateBuiltInDecoration(glslangBuiltIn, false);
2962 break;
2963 default:
2964 // Capabilities were already generated when the struct was declared.
2965 break;
2966 }
John Kessenichebb50532016-05-16 19:22:05 -06002967}
2968
John Kessenich6fccb3c2016-09-19 16:01:41 -06002969bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002970{
John Kessenicheee9d532016-09-19 18:09:30 -06002971 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002972}
2973
John Kessenichd41993d2017-09-10 15:21:05 -06002974// Does parameter need a place to keep writes, separate from the original?
2975bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
2976{
2977 return qualifier != glslang::EvqConstReadOnly;
2978}
2979
2980// Is parameter pass-by-original?
2981bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
2982 bool implicitThisParam)
2983{
2984 if (implicitThisParam) // implicit this
2985 return true;
2986 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
2987 return false;
2988 return paramType.containsOpaque() || // sampler, etc.
2989 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
2990}
2991
John Kessenich140f3df2015-06-26 16:58:36 -06002992// Make all the functions, skeletally, without actually visiting their bodies.
2993void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2994{
John Kessenichfad62972017-07-18 02:35:46 -06002995 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
2996 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
2997 if (paramPrecision != spv::NoPrecision)
2998 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06002999 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003000 };
3001
John Kessenich140f3df2015-06-26 16:58:36 -06003002 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3003 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003004 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003005 continue;
3006
3007 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003008 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003009 //
qining25262b32016-05-06 17:25:16 -04003010 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003011 // function. What it is an address of varies:
3012 //
John Kessenich4bf71552016-09-02 11:20:21 -06003013 // - "in" parameters not marked as "const" can be written to without modifying the calling
3014 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003015 //
3016 // - "const in" parameters can just be the r-value, as no writes need occur.
3017 //
John Kessenich4bf71552016-09-02 11:20:21 -06003018 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3019 // 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 -06003020
3021 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003022 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003023 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3024
John Kessenichfad62972017-07-18 02:35:46 -06003025 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3026 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003027
John Kessenichfad62972017-07-18 02:35:46 -06003028 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003029 for (int p = 0; p < (int)parameters.size(); ++p) {
3030 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3031 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003032 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003033 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003034 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003035 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3036 else
John Kessenich4bf71552016-09-02 11:20:21 -06003037 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003038 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003039 paramTypes.push_back(typeId);
3040 }
3041
3042 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003043 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3044 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003045 glslFunction->getName().c_str(), paramTypes,
3046 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003047 if (implicitThis)
3048 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003049
3050 // Track function to emit/call later
3051 functionMap[glslFunction->getName().c_str()] = function;
3052
3053 // Set the parameter id's
3054 for (int p = 0; p < (int)parameters.size(); ++p) {
3055 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3056 // give a name too
3057 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3058 }
3059 }
3060}
3061
3062// Process all the initializers, while skipping the functions and link objects
3063void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3064{
3065 builder.setBuildPoint(shaderEntry->getLastBlock());
3066 for (int i = 0; i < (int)initializers.size(); ++i) {
3067 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3068 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3069
3070 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003071 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003072 initializer->traverse(this);
3073 }
3074 }
3075}
3076
3077// Process all the functions, while skipping initializers.
3078void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3079{
3080 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3081 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003082 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003083 node->traverse(this);
3084 }
3085}
3086
3087void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3088{
qining25262b32016-05-06 17:25:16 -04003089 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003090 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003091 currentFunction = functionMap[node->getName().c_str()];
3092 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003093 builder.setBuildPoint(functionBlock);
3094}
3095
Rex Xu04db3f52015-09-16 11:44:02 +08003096void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003097{
Rex Xufc618912015-09-09 16:42:49 +08003098 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003099
3100 glslang::TSampler sampler = {};
3101 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003102 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003103 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3104 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3105 }
3106
John Kessenich140f3df2015-06-26 16:58:36 -06003107 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3108 builder.clearAccessChain();
3109 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003110
3111 // Special case l-value operands
3112 bool lvalue = false;
3113 switch (node.getOp()) {
3114 case glslang::EOpImageAtomicAdd:
3115 case glslang::EOpImageAtomicMin:
3116 case glslang::EOpImageAtomicMax:
3117 case glslang::EOpImageAtomicAnd:
3118 case glslang::EOpImageAtomicOr:
3119 case glslang::EOpImageAtomicXor:
3120 case glslang::EOpImageAtomicExchange:
3121 case glslang::EOpImageAtomicCompSwap:
3122 if (i == 0)
3123 lvalue = true;
3124 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003125 case glslang::EOpSparseImageLoad:
3126 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3127 lvalue = true;
3128 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003129 case glslang::EOpSparseTexture:
3130 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3131 lvalue = true;
3132 break;
3133 case glslang::EOpSparseTextureClamp:
3134 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3135 lvalue = true;
3136 break;
3137 case glslang::EOpSparseTextureLod:
3138 case glslang::EOpSparseTextureOffset:
3139 if (i == 3)
3140 lvalue = true;
3141 break;
3142 case glslang::EOpSparseTextureFetch:
3143 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3144 lvalue = true;
3145 break;
3146 case glslang::EOpSparseTextureFetchOffset:
3147 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3148 lvalue = true;
3149 break;
3150 case glslang::EOpSparseTextureLodOffset:
3151 case glslang::EOpSparseTextureGrad:
3152 case glslang::EOpSparseTextureOffsetClamp:
3153 if (i == 4)
3154 lvalue = true;
3155 break;
3156 case glslang::EOpSparseTextureGradOffset:
3157 case glslang::EOpSparseTextureGradClamp:
3158 if (i == 5)
3159 lvalue = true;
3160 break;
3161 case glslang::EOpSparseTextureGradOffsetClamp:
3162 if (i == 6)
3163 lvalue = true;
3164 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003165 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003166 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3167 lvalue = true;
3168 break;
3169 case glslang::EOpSparseTextureGatherOffset:
3170 case glslang::EOpSparseTextureGatherOffsets:
3171 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3172 lvalue = true;
3173 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003174#ifdef AMD_EXTENSIONS
3175 case glslang::EOpSparseTextureGatherLod:
3176 if (i == 3)
3177 lvalue = true;
3178 break;
3179 case glslang::EOpSparseTextureGatherLodOffset:
3180 case glslang::EOpSparseTextureGatherLodOffsets:
3181 if (i == 4)
3182 lvalue = true;
3183 break;
Rex Xu129799a2017-07-05 17:23:28 +08003184 case glslang::EOpSparseImageLoadLod:
3185 if (i == 3)
3186 lvalue = true;
3187 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003188#endif
Rex Xufc618912015-09-09 16:42:49 +08003189 default:
3190 break;
3191 }
3192
Rex Xu6b86d492015-09-16 17:48:22 +08003193 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003194 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003195 else
John Kessenich32cfd492016-02-02 12:37:46 -07003196 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003197 }
3198}
3199
John Kessenichfc51d282015-08-19 13:34:18 -06003200void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003201{
John Kessenichfc51d282015-08-19 13:34:18 -06003202 builder.clearAccessChain();
3203 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003204 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003205}
John Kessenich140f3df2015-06-26 16:58:36 -06003206
John Kessenichfc51d282015-08-19 13:34:18 -06003207spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3208{
John Kesseniche485c7a2017-05-31 18:50:53 -06003209 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003210 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003211
3212 builder.setLine(node->getLoc().line);
3213
John Kessenich8c8505c2016-07-26 12:50:38 -06003214 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003215
John Kessenichfc51d282015-08-19 13:34:18 -06003216 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003217 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3218 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3219 std::vector<spv::Id> arguments;
3220 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003221 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003222 else
3223 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003224 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003225
3226 spv::Builder::TextureParameters params = { };
3227 params.sampler = arguments[0];
3228
Rex Xu04db3f52015-09-16 11:44:02 +08003229 glslang::TCrackedTextureOp cracked;
3230 node->crackTexture(sampler, cracked);
3231
amhagan05506bb2017-06-13 16:53:02 -04003232 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003233
John Kessenichfc51d282015-08-19 13:34:18 -06003234 // Check for queries
3235 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003236 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3237 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003238 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003239
John Kessenichfc51d282015-08-19 13:34:18 -06003240 switch (node->getOp()) {
3241 case glslang::EOpImageQuerySize:
3242 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003243 if (arguments.size() > 1) {
3244 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003245 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003246 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003247 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003248 case glslang::EOpImageQuerySamples:
3249 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003250 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003251 case glslang::EOpTextureQueryLod:
3252 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003253 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003254 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003255 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003256 case glslang::EOpSparseTexelsResident:
3257 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003258 default:
3259 assert(0);
3260 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003261 }
John Kessenich140f3df2015-06-26 16:58:36 -06003262 }
3263
Rex Xufc618912015-09-09 16:42:49 +08003264 // Check for image functions other than queries
3265 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003266 std::vector<spv::Id> operands;
3267 auto opIt = arguments.begin();
3268 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003269
3270 // Handle subpass operations
3271 // TODO: GLSL should change to have the "MS" only on the type rather than the
3272 // built-in function.
3273 if (cracked.subpass) {
3274 // add on the (0,0) coordinate
3275 spv::Id zero = builder.makeIntConstant(0);
3276 std::vector<spv::Id> comps;
3277 comps.push_back(zero);
3278 comps.push_back(zero);
3279 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3280 if (sampler.ms) {
3281 operands.push_back(spv::ImageOperandsSampleMask);
3282 operands.push_back(*(opIt++));
3283 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003284 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003285 }
3286
John Kessenich56bab042015-09-16 10:54:31 -06003287 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003288#ifdef AMD_EXTENSIONS
3289 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3290#else
John Kessenich56bab042015-09-16 10:54:31 -06003291 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003292#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003293 if (sampler.ms) {
3294 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003295 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003296#ifdef AMD_EXTENSIONS
3297 } else if (cracked.lod) {
3298 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3299 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3300
3301 operands.push_back(spv::ImageOperandsLodMask);
3302 operands.push_back(*opIt);
3303#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003304 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003305 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3306 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003307 return builder.createOp(spv::OpImageRead, resultType(), operands);
Rex Xu129799a2017-07-05 17:23:28 +08003308#ifdef AMD_EXTENSIONS
3309 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3310#else
John Kessenich56bab042015-09-16 10:54:31 -06003311 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003312#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003313 if (sampler.ms) {
3314 operands.push_back(*(opIt + 1));
3315 operands.push_back(spv::ImageOperandsSampleMask);
3316 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003317#ifdef AMD_EXTENSIONS
3318 } else if (cracked.lod) {
3319 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3320 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3321
3322 operands.push_back(*(opIt + 1));
3323 operands.push_back(spv::ImageOperandsLodMask);
3324 operands.push_back(*opIt);
3325#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003326 } else
3327 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003328 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003329 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3330 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003331 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003332#ifdef AMD_EXTENSIONS
3333 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3334#else
Rex Xu5eafa472016-02-19 22:24:03 +08003335 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003336#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003337 builder.addCapability(spv::CapabilitySparseResidency);
3338 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3339 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3340
3341 if (sampler.ms) {
3342 operands.push_back(spv::ImageOperandsSampleMask);
3343 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003344#ifdef AMD_EXTENSIONS
3345 } else if (cracked.lod) {
3346 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3347 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3348
3349 operands.push_back(spv::ImageOperandsLodMask);
3350 operands.push_back(*opIt++);
3351#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003352 }
3353
3354 // Create the return type that was a special structure
3355 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003356 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003357 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3358 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3359
3360 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3361
3362 // Decode the return type
3363 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3364 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003365 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003366 // Process image atomic operations
3367
3368 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3369 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003370 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003371
John Kessenich8c8505c2016-07-26 12:50:38 -06003372 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003373 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003374
3375 std::vector<spv::Id> operands;
3376 operands.push_back(pointer);
3377 for (; opIt != arguments.end(); ++opIt)
3378 operands.push_back(*opIt);
3379
John Kessenich8c8505c2016-07-26 12:50:38 -06003380 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003381 }
3382 }
3383
amhagan05506bb2017-06-13 16:53:02 -04003384#ifdef AMD_EXTENSIONS
3385 // Check for fragment mask functions other than queries
3386 if (cracked.fragMask) {
3387 assert(sampler.ms);
3388
3389 auto opIt = arguments.begin();
3390 std::vector<spv::Id> operands;
3391
3392 // Extract the image if necessary
3393 if (builder.isSampledImage(params.sampler))
3394 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3395
3396 operands.push_back(params.sampler);
3397 ++opIt;
3398
3399 if (sampler.isSubpass()) {
3400 // add on the (0,0) coordinate
3401 spv::Id zero = builder.makeIntConstant(0);
3402 std::vector<spv::Id> comps;
3403 comps.push_back(zero);
3404 comps.push_back(zero);
3405 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3406 }
3407
3408 for (; opIt != arguments.end(); ++opIt)
3409 operands.push_back(*opIt);
3410
3411 spv::Op fragMaskOp = spv::OpNop;
3412 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3413 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3414 else if (node->getOp() == glslang::EOpFragmentFetch)
3415 fragMaskOp = spv::OpFragmentFetchAMD;
3416
3417 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3418 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3419 return builder.createOp(fragMaskOp, resultType(), operands);
3420 }
3421#endif
3422
Rex Xufc618912015-09-09 16:42:49 +08003423 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003424 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003425 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3426
John Kessenichfc51d282015-08-19 13:34:18 -06003427 // check for bias argument
3428 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003429#ifdef AMD_EXTENSIONS
3430 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3431#else
Rex Xu71519fe2015-11-11 15:35:47 +08003432 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003433#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003434 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003435#ifdef AMD_EXTENSIONS
3436 if (cracked.gather)
3437 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3438#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003439 if (cracked.offset)
3440 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003441#ifdef AMD_EXTENSIONS
3442 else if (cracked.offsets)
3443 ++nonBiasArgCount;
3444#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003445 if (cracked.grad)
3446 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003447 if (cracked.lodClamp)
3448 ++nonBiasArgCount;
3449 if (sparse)
3450 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003451
3452 if ((int)arguments.size() > nonBiasArgCount)
3453 bias = true;
3454 }
3455
John Kessenicha5c33d62016-06-02 23:45:21 -06003456 // See if the sampler param should really be just the SPV image part
3457 if (cracked.fetch) {
3458 // a fetch needs to have the image extracted first
3459 if (builder.isSampledImage(params.sampler))
3460 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3461 }
3462
Rex Xu225e0fc2016-11-17 17:47:59 +08003463#ifdef AMD_EXTENSIONS
3464 if (cracked.gather) {
3465 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3466 if (bias || cracked.lod ||
3467 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3468 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003469 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003470 }
3471 }
3472#endif
3473
John Kessenichfc51d282015-08-19 13:34:18 -06003474 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003475
John Kessenichfc51d282015-08-19 13:34:18 -06003476 params.coords = arguments[1];
3477 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003478 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003479
3480 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003481 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003482 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003483 ++extraArgs;
3484 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003485 params.Dref = arguments[2];
3486 ++extraArgs;
3487 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003488 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003489 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003490 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003491 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003492 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003493 dRefComp = builder.getNumComponents(params.coords) - 1;
3494 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003495 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3496 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003497
3498 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003499 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003500 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003501 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003502 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3503 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3504 noImplicitLod = true;
3505 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003506
3507 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003508 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003509 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003510 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003511 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003512
3513 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003514 if (cracked.grad) {
3515 params.gradX = arguments[2 + extraArgs];
3516 params.gradY = arguments[3 + extraArgs];
3517 extraArgs += 2;
3518 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003519
3520 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003521 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003522 params.offset = arguments[2 + extraArgs];
3523 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003524 } else if (cracked.offsets) {
3525 params.offsets = arguments[2 + extraArgs];
3526 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003527 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003528
3529 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003530 if (cracked.lodClamp) {
3531 params.lodClamp = arguments[2 + extraArgs];
3532 ++extraArgs;
3533 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003534
3535 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003536 if (sparse) {
3537 params.texelOut = arguments[2 + extraArgs];
3538 ++extraArgs;
3539 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003540
John Kessenich76d4dfc2016-06-16 12:43:23 -06003541 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003542 if (cracked.gather && ! sampler.shadow) {
3543 // default component is 0, if missing, otherwise an argument
3544 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003545 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003546 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003547 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003548 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003549 }
3550
3551 // bias
3552 if (bias) {
3553 params.bias = arguments[2 + extraArgs];
3554 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003555 }
John Kessenichfc51d282015-08-19 13:34:18 -06003556
John Kessenich65336482016-06-16 14:06:26 -06003557 // projective component (might not to move)
3558 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3559 // are divided by the last component of P."
3560 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3561 // unused components will appear after all used components."
3562 if (cracked.proj) {
3563 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3564 int projTargetComp;
3565 switch (sampler.dim) {
3566 case glslang::Esd1D: projTargetComp = 1; break;
3567 case glslang::Esd2D: projTargetComp = 2; break;
3568 case glslang::EsdRect: projTargetComp = 2; break;
3569 default: projTargetComp = projSourceComp; break;
3570 }
3571 // copy the projective coordinate if we have to
3572 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003573 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003574 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3575 projSourceComp);
3576 params.coords = builder.createCompositeInsert(projComp, params.coords,
3577 builder.getTypeId(params.coords), projTargetComp);
3578 }
3579 }
3580
John Kessenich8c8505c2016-07-26 12:50:38 -06003581 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003582}
3583
3584spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3585{
3586 // Grab the function's pointer from the previously created function
3587 spv::Function* function = functionMap[node->getName().c_str()];
3588 if (! function)
3589 return 0;
3590
3591 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3592 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3593
3594 // See comments in makeFunctions() for details about the semantics for parameter passing.
3595 //
3596 // These imply we need a four step process:
3597 // 1. Evaluate the arguments
3598 // 2. Allocate and make copies of in, out, and inout arguments
3599 // 3. Make the call
3600 // 4. Copy back the results
3601
3602 // 1. Evaluate the arguments
3603 std::vector<spv::Builder::AccessChain> lValues;
3604 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003605 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003606 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003607 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003608 // build l-value
3609 builder.clearAccessChain();
3610 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003611 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003612 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
3613 if (writableParam(qualifiers[a]) ||
3614 originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003615 // save l-value
3616 lValues.push_back(builder.getAccessChain());
3617 } else {
3618 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003619 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003620 }
3621 }
3622
3623 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3624 // copy the original into that space.
3625 //
3626 // Also, build up the list of actual arguments to pass in for the call
3627 int lValueCount = 0;
3628 int rValueCount = 0;
3629 std::vector<spv::Id> spvArgs;
3630 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003631 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003632 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003633 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003634 builder.setAccessChain(lValues[lValueCount]);
3635 arg = builder.accessChainGetLValue();
3636 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003637 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003638 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003639 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3640 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3641 // need to copy the input into output space
3642 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003643 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003644 builder.clearAccessChain();
3645 builder.setAccessChainLValue(arg);
3646 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003647 }
3648 ++lValueCount;
3649 } else {
3650 arg = rValues[rValueCount];
3651 ++rValueCount;
3652 }
3653 spvArgs.push_back(arg);
3654 }
3655
3656 // 3. Make the call.
3657 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003658 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003659
3660 // 4. Copy back out an "out" arguments.
3661 lValueCount = 0;
3662 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003663 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06003664 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
3665 ++lValueCount;
3666 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003667 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3668 spv::Id copy = builder.createLoad(spvArgs[a]);
3669 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003670 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003671 }
3672 ++lValueCount;
3673 }
3674 }
3675
3676 return result;
3677}
3678
3679// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003680spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3681 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003682 spv::Id typeId, spv::Id left, spv::Id right,
3683 glslang::TBasicType typeProxy, bool reduceComparison)
3684{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003685#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003686 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003687 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3688#else
Rex Xucabbb782017-03-24 13:41:14 +08003689 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003690 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003691#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003692 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003693
3694 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003695 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003696 bool comparison = false;
3697
3698 switch (op) {
3699 case glslang::EOpAdd:
3700 case glslang::EOpAddAssign:
3701 if (isFloat)
3702 binOp = spv::OpFAdd;
3703 else
3704 binOp = spv::OpIAdd;
3705 break;
3706 case glslang::EOpSub:
3707 case glslang::EOpSubAssign:
3708 if (isFloat)
3709 binOp = spv::OpFSub;
3710 else
3711 binOp = spv::OpISub;
3712 break;
3713 case glslang::EOpMul:
3714 case glslang::EOpMulAssign:
3715 if (isFloat)
3716 binOp = spv::OpFMul;
3717 else
3718 binOp = spv::OpIMul;
3719 break;
3720 case glslang::EOpVectorTimesScalar:
3721 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003722 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003723 if (builder.isVector(right))
3724 std::swap(left, right);
3725 assert(builder.isScalar(right));
3726 needMatchingVectors = false;
3727 binOp = spv::OpVectorTimesScalar;
3728 } else
3729 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003730 break;
3731 case glslang::EOpVectorTimesMatrix:
3732 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003733 binOp = spv::OpVectorTimesMatrix;
3734 break;
3735 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003736 binOp = spv::OpMatrixTimesVector;
3737 break;
3738 case glslang::EOpMatrixTimesScalar:
3739 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003740 binOp = spv::OpMatrixTimesScalar;
3741 break;
3742 case glslang::EOpMatrixTimesMatrix:
3743 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003744 binOp = spv::OpMatrixTimesMatrix;
3745 break;
3746 case glslang::EOpOuterProduct:
3747 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003748 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003749 break;
3750
3751 case glslang::EOpDiv:
3752 case glslang::EOpDivAssign:
3753 if (isFloat)
3754 binOp = spv::OpFDiv;
3755 else if (isUnsigned)
3756 binOp = spv::OpUDiv;
3757 else
3758 binOp = spv::OpSDiv;
3759 break;
3760 case glslang::EOpMod:
3761 case glslang::EOpModAssign:
3762 if (isFloat)
3763 binOp = spv::OpFMod;
3764 else if (isUnsigned)
3765 binOp = spv::OpUMod;
3766 else
3767 binOp = spv::OpSMod;
3768 break;
3769 case glslang::EOpRightShift:
3770 case glslang::EOpRightShiftAssign:
3771 if (isUnsigned)
3772 binOp = spv::OpShiftRightLogical;
3773 else
3774 binOp = spv::OpShiftRightArithmetic;
3775 break;
3776 case glslang::EOpLeftShift:
3777 case glslang::EOpLeftShiftAssign:
3778 binOp = spv::OpShiftLeftLogical;
3779 break;
3780 case glslang::EOpAnd:
3781 case glslang::EOpAndAssign:
3782 binOp = spv::OpBitwiseAnd;
3783 break;
3784 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003785 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003786 binOp = spv::OpLogicalAnd;
3787 break;
3788 case glslang::EOpInclusiveOr:
3789 case glslang::EOpInclusiveOrAssign:
3790 binOp = spv::OpBitwiseOr;
3791 break;
3792 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003793 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003794 binOp = spv::OpLogicalOr;
3795 break;
3796 case glslang::EOpExclusiveOr:
3797 case glslang::EOpExclusiveOrAssign:
3798 binOp = spv::OpBitwiseXor;
3799 break;
3800 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003801 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003802 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003803 break;
3804
3805 case glslang::EOpLessThan:
3806 case glslang::EOpGreaterThan:
3807 case glslang::EOpLessThanEqual:
3808 case glslang::EOpGreaterThanEqual:
3809 case glslang::EOpEqual:
3810 case glslang::EOpNotEqual:
3811 case glslang::EOpVectorEqual:
3812 case glslang::EOpVectorNotEqual:
3813 comparison = true;
3814 break;
3815 default:
3816 break;
3817 }
3818
John Kessenich7c1aa102015-10-15 13:29:11 -06003819 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003820 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003821 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003822 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003823 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003824
3825 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003826 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003827 builder.promoteScalar(precision, left, right);
3828
qining25262b32016-05-06 17:25:16 -04003829 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3830 addDecoration(result, noContraction);
3831 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003832 }
3833
3834 if (! comparison)
3835 return 0;
3836
John Kessenich7c1aa102015-10-15 13:29:11 -06003837 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003838
John Kessenich4583b612016-08-07 19:14:22 -06003839 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3840 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003841 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003842
3843 switch (op) {
3844 case glslang::EOpLessThan:
3845 if (isFloat)
3846 binOp = spv::OpFOrdLessThan;
3847 else if (isUnsigned)
3848 binOp = spv::OpULessThan;
3849 else
3850 binOp = spv::OpSLessThan;
3851 break;
3852 case glslang::EOpGreaterThan:
3853 if (isFloat)
3854 binOp = spv::OpFOrdGreaterThan;
3855 else if (isUnsigned)
3856 binOp = spv::OpUGreaterThan;
3857 else
3858 binOp = spv::OpSGreaterThan;
3859 break;
3860 case glslang::EOpLessThanEqual:
3861 if (isFloat)
3862 binOp = spv::OpFOrdLessThanEqual;
3863 else if (isUnsigned)
3864 binOp = spv::OpULessThanEqual;
3865 else
3866 binOp = spv::OpSLessThanEqual;
3867 break;
3868 case glslang::EOpGreaterThanEqual:
3869 if (isFloat)
3870 binOp = spv::OpFOrdGreaterThanEqual;
3871 else if (isUnsigned)
3872 binOp = spv::OpUGreaterThanEqual;
3873 else
3874 binOp = spv::OpSGreaterThanEqual;
3875 break;
3876 case glslang::EOpEqual:
3877 case glslang::EOpVectorEqual:
3878 if (isFloat)
3879 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003880 else if (isBool)
3881 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003882 else
3883 binOp = spv::OpIEqual;
3884 break;
3885 case glslang::EOpNotEqual:
3886 case glslang::EOpVectorNotEqual:
3887 if (isFloat)
3888 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003889 else if (isBool)
3890 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003891 else
3892 binOp = spv::OpINotEqual;
3893 break;
3894 default:
3895 break;
3896 }
3897
qining25262b32016-05-06 17:25:16 -04003898 if (binOp != spv::OpNop) {
3899 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3900 addDecoration(result, noContraction);
3901 return builder.setPrecision(result, precision);
3902 }
John Kessenich140f3df2015-06-26 16:58:36 -06003903
3904 return 0;
3905}
3906
John Kessenich04bb8a02015-12-12 12:28:14 -07003907//
3908// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3909// These can be any of:
3910//
3911// matrix * scalar
3912// scalar * matrix
3913// matrix * matrix linear algebraic
3914// matrix * vector
3915// vector * matrix
3916// matrix * matrix componentwise
3917// matrix op matrix op in {+, -, /}
3918// matrix op scalar op in {+, -, /}
3919// scalar op matrix op in {+, -, /}
3920//
qining25262b32016-05-06 17:25:16 -04003921spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07003922{
3923 bool firstClass = true;
3924
3925 // First, handle first-class matrix operations (* and matrix/scalar)
3926 switch (op) {
3927 case spv::OpFDiv:
3928 if (builder.isMatrix(left) && builder.isScalar(right)) {
3929 // turn matrix / scalar into a multiply...
3930 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3931 op = spv::OpMatrixTimesScalar;
3932 } else
3933 firstClass = false;
3934 break;
3935 case spv::OpMatrixTimesScalar:
3936 if (builder.isMatrix(right))
3937 std::swap(left, right);
3938 assert(builder.isScalar(right));
3939 break;
3940 case spv::OpVectorTimesMatrix:
3941 assert(builder.isVector(left));
3942 assert(builder.isMatrix(right));
3943 break;
3944 case spv::OpMatrixTimesVector:
3945 assert(builder.isMatrix(left));
3946 assert(builder.isVector(right));
3947 break;
3948 case spv::OpMatrixTimesMatrix:
3949 assert(builder.isMatrix(left));
3950 assert(builder.isMatrix(right));
3951 break;
3952 default:
3953 firstClass = false;
3954 break;
3955 }
3956
qining25262b32016-05-06 17:25:16 -04003957 if (firstClass) {
3958 spv::Id result = builder.createBinOp(op, typeId, left, right);
3959 addDecoration(result, noContraction);
3960 return builder.setPrecision(result, precision);
3961 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003962
LoopDawg592860c2016-06-09 08:57:35 -06003963 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003964 // The result type of all of them is the same type as the (a) matrix operand.
3965 // The algorithm is to:
3966 // - break the matrix(es) into vectors
3967 // - smear any scalar to a vector
3968 // - do vector operations
3969 // - make a matrix out the vector results
3970 switch (op) {
3971 case spv::OpFAdd:
3972 case spv::OpFSub:
3973 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003974 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003975 case spv::OpFMul:
3976 {
3977 // one time set up...
3978 bool leftMat = builder.isMatrix(left);
3979 bool rightMat = builder.isMatrix(right);
3980 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3981 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3982 spv::Id scalarType = builder.getScalarTypeId(typeId);
3983 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3984 std::vector<spv::Id> results;
3985 spv::Id smearVec = spv::NoResult;
3986 if (builder.isScalar(left))
3987 smearVec = builder.smearScalar(precision, left, vecType);
3988 else if (builder.isScalar(right))
3989 smearVec = builder.smearScalar(precision, right, vecType);
3990
3991 // do each vector op
3992 for (unsigned int c = 0; c < numCols; ++c) {
3993 std::vector<unsigned int> indexes;
3994 indexes.push_back(c);
3995 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3996 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003997 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3998 addDecoration(result, noContraction);
3999 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004000 }
4001
4002 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004003 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07004004 }
4005 default:
4006 assert(0);
4007 return spv::NoResult;
4008 }
4009}
4010
qining25262b32016-05-06 17:25:16 -04004011spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004012{
4013 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004014 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004015 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004016#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004017 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004018 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4019#else
Rex Xucabbb782017-03-24 13:41:14 +08004020 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08004021 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004022#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004023
4024 switch (op) {
4025 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004026 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004027 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004028 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04004029 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004030 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004031 unaryOp = spv::OpSNegate;
4032 break;
4033
4034 case glslang::EOpLogicalNot:
4035 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004036 unaryOp = spv::OpLogicalNot;
4037 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004038 case glslang::EOpBitwiseNot:
4039 unaryOp = spv::OpNot;
4040 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004041
John Kessenich140f3df2015-06-26 16:58:36 -06004042 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004043 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004044 break;
4045 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004046 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004047 break;
4048 case glslang::EOpTranspose:
4049 unaryOp = spv::OpTranspose;
4050 break;
4051
4052 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004053 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004054 break;
4055 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004056 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004057 break;
4058 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004059 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004060 break;
4061 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004062 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004063 break;
4064 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004065 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004066 break;
4067 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004068 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004069 break;
4070 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004071 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004072 break;
4073 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004074 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004075 break;
4076
4077 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004078 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004079 break;
4080 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004081 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004082 break;
4083 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004084 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004085 break;
4086 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004087 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004088 break;
4089 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004090 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004091 break;
4092 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004093 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004094 break;
4095
4096 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004097 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004098 break;
4099 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004100 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004101 break;
4102
4103 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004104 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004105 break;
4106 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004107 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004108 break;
4109 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004110 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004111 break;
4112 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004113 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004114 break;
4115 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004116 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004117 break;
4118 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004119 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004120 break;
4121
4122 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004123 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004124 break;
4125 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004126 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004127 break;
4128 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004129 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004130 break;
4131 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004132 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004133 break;
4134 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004135 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004136 break;
4137 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004138 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004139 break;
4140
4141 case glslang::EOpIsNan:
4142 unaryOp = spv::OpIsNan;
4143 break;
4144 case glslang::EOpIsInf:
4145 unaryOp = spv::OpIsInf;
4146 break;
LoopDawg592860c2016-06-09 08:57:35 -06004147 case glslang::EOpIsFinite:
4148 unaryOp = spv::OpIsFinite;
4149 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004150
Rex Xucbc426e2015-12-15 16:03:10 +08004151 case glslang::EOpFloatBitsToInt:
4152 case glslang::EOpFloatBitsToUint:
4153 case glslang::EOpIntBitsToFloat:
4154 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004155 case glslang::EOpDoubleBitsToInt64:
4156 case glslang::EOpDoubleBitsToUint64:
4157 case glslang::EOpInt64BitsToDouble:
4158 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004159#ifdef AMD_EXTENSIONS
4160 case glslang::EOpFloat16BitsToInt16:
4161 case glslang::EOpFloat16BitsToUint16:
4162 case glslang::EOpInt16BitsToFloat16:
4163 case glslang::EOpUint16BitsToFloat16:
4164#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004165 unaryOp = spv::OpBitcast;
4166 break;
4167
John Kessenich140f3df2015-06-26 16:58:36 -06004168 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004169 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004170 break;
4171 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004172 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004173 break;
4174 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004175 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004176 break;
4177 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004178 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004179 break;
4180 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004181 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004182 break;
4183 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004184 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004185 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004186 case glslang::EOpPackSnorm4x8:
4187 libCall = spv::GLSLstd450PackSnorm4x8;
4188 break;
4189 case glslang::EOpUnpackSnorm4x8:
4190 libCall = spv::GLSLstd450UnpackSnorm4x8;
4191 break;
4192 case glslang::EOpPackUnorm4x8:
4193 libCall = spv::GLSLstd450PackUnorm4x8;
4194 break;
4195 case glslang::EOpUnpackUnorm4x8:
4196 libCall = spv::GLSLstd450UnpackUnorm4x8;
4197 break;
4198 case glslang::EOpPackDouble2x32:
4199 libCall = spv::GLSLstd450PackDouble2x32;
4200 break;
4201 case glslang::EOpUnpackDouble2x32:
4202 libCall = spv::GLSLstd450UnpackDouble2x32;
4203 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004204
Rex Xu8ff43de2016-04-22 16:51:45 +08004205 case glslang::EOpPackInt2x32:
4206 case glslang::EOpUnpackInt2x32:
4207 case glslang::EOpPackUint2x32:
4208 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004209 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004210 break;
4211
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004212#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004213 case glslang::EOpPackInt2x16:
4214 case glslang::EOpUnpackInt2x16:
4215 case glslang::EOpPackUint2x16:
4216 case glslang::EOpUnpackUint2x16:
4217 case glslang::EOpPackInt4x16:
4218 case glslang::EOpUnpackInt4x16:
4219 case glslang::EOpPackUint4x16:
4220 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004221 case glslang::EOpPackFloat2x16:
4222 case glslang::EOpUnpackFloat2x16:
4223 unaryOp = spv::OpBitcast;
4224 break;
4225#endif
4226
John Kessenich140f3df2015-06-26 16:58:36 -06004227 case glslang::EOpDPdx:
4228 unaryOp = spv::OpDPdx;
4229 break;
4230 case glslang::EOpDPdy:
4231 unaryOp = spv::OpDPdy;
4232 break;
4233 case glslang::EOpFwidth:
4234 unaryOp = spv::OpFwidth;
4235 break;
4236 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004237 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004238 unaryOp = spv::OpDPdxFine;
4239 break;
4240 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004241 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004242 unaryOp = spv::OpDPdyFine;
4243 break;
4244 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004245 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004246 unaryOp = spv::OpFwidthFine;
4247 break;
4248 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004249 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004250 unaryOp = spv::OpDPdxCoarse;
4251 break;
4252 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004253 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004254 unaryOp = spv::OpDPdyCoarse;
4255 break;
4256 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004257 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004258 unaryOp = spv::OpFwidthCoarse;
4259 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004260 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004261 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004262 libCall = spv::GLSLstd450InterpolateAtCentroid;
4263 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004264 case glslang::EOpAny:
4265 unaryOp = spv::OpAny;
4266 break;
4267 case glslang::EOpAll:
4268 unaryOp = spv::OpAll;
4269 break;
4270
4271 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004272 if (isFloat)
4273 libCall = spv::GLSLstd450FAbs;
4274 else
4275 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004276 break;
4277 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004278 if (isFloat)
4279 libCall = spv::GLSLstd450FSign;
4280 else
4281 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004282 break;
4283
John Kessenichfc51d282015-08-19 13:34:18 -06004284 case glslang::EOpAtomicCounterIncrement:
4285 case glslang::EOpAtomicCounterDecrement:
4286 case glslang::EOpAtomicCounter:
4287 {
4288 // Handle all of the atomics in one place, in createAtomicOperation()
4289 std::vector<spv::Id> operands;
4290 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004291 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004292 }
4293
John Kessenichfc51d282015-08-19 13:34:18 -06004294 case glslang::EOpBitFieldReverse:
4295 unaryOp = spv::OpBitReverse;
4296 break;
4297 case glslang::EOpBitCount:
4298 unaryOp = spv::OpBitCount;
4299 break;
4300 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004301 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004302 break;
4303 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004304 if (isUnsigned)
4305 libCall = spv::GLSLstd450FindUMsb;
4306 else
4307 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004308 break;
4309
Rex Xu574ab042016-04-14 16:53:07 +08004310 case glslang::EOpBallot:
4311 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004312 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004313 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004314 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004315#ifdef AMD_EXTENSIONS
4316 case glslang::EOpMinInvocations:
4317 case glslang::EOpMaxInvocations:
4318 case glslang::EOpAddInvocations:
4319 case glslang::EOpMinInvocationsNonUniform:
4320 case glslang::EOpMaxInvocationsNonUniform:
4321 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004322 case glslang::EOpMinInvocationsInclusiveScan:
4323 case glslang::EOpMaxInvocationsInclusiveScan:
4324 case glslang::EOpAddInvocationsInclusiveScan:
4325 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4326 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4327 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4328 case glslang::EOpMinInvocationsExclusiveScan:
4329 case glslang::EOpMaxInvocationsExclusiveScan:
4330 case glslang::EOpAddInvocationsExclusiveScan:
4331 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4332 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4333 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004334#endif
Rex Xu51596642016-09-21 18:56:12 +08004335 {
4336 std::vector<spv::Id> operands;
4337 operands.push_back(operand);
4338 return createInvocationsOperation(op, typeId, operands, typeProxy);
4339 }
Rex Xu9d93a232016-05-05 12:30:44 +08004340
4341#ifdef AMD_EXTENSIONS
4342 case glslang::EOpMbcnt:
4343 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4344 libCall = spv::MbcntAMD;
4345 break;
4346
4347 case glslang::EOpCubeFaceIndex:
4348 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4349 libCall = spv::CubeFaceIndexAMD;
4350 break;
4351
4352 case glslang::EOpCubeFaceCoord:
4353 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4354 libCall = spv::CubeFaceCoordAMD;
4355 break;
4356#endif
Rex Xu338b1852016-05-05 20:38:33 +08004357
John Kessenich140f3df2015-06-26 16:58:36 -06004358 default:
4359 return 0;
4360 }
4361
4362 spv::Id id;
4363 if (libCall >= 0) {
4364 std::vector<spv::Id> args;
4365 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004366 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004367 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004368 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004369 }
John Kessenich140f3df2015-06-26 16:58:36 -06004370
qining25262b32016-05-06 17:25:16 -04004371 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004372 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004373}
4374
John Kessenich7a53f762016-01-20 11:19:27 -07004375// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004376spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07004377{
4378 // Handle unary operations vector by vector.
4379 // The result type is the same type as the original type.
4380 // The algorithm is to:
4381 // - break the matrix into vectors
4382 // - apply the operation to each vector
4383 // - make a matrix out the vector results
4384
4385 // get the types sorted out
4386 int numCols = builder.getNumColumns(operand);
4387 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004388 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4389 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004390 std::vector<spv::Id> results;
4391
4392 // do each vector op
4393 for (int c = 0; c < numCols; ++c) {
4394 std::vector<unsigned int> indexes;
4395 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004396 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4397 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4398 addDecoration(destVec, noContraction);
4399 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004400 }
4401
4402 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004403 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004404}
4405
Rex Xu73e3ce72016-04-27 18:48:17 +08004406spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destType, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004407{
4408 spv::Op convOp = spv::OpNop;
4409 spv::Id zero = 0;
4410 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004411 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004412
4413 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4414
4415 switch (op) {
4416 case glslang::EOpConvIntToBool:
4417 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004418 case glslang::EOpConvInt64ToBool:
4419 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004420#ifdef AMD_EXTENSIONS
4421 case glslang::EOpConvInt16ToBool:
4422 case glslang::EOpConvUint16ToBool:
4423#endif
4424 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4425 zero = builder.makeUint64Constant(0);
4426#ifdef AMD_EXTENSIONS
4427 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4428 zero = builder.makeUint16Constant(0);
4429#endif
4430 else
4431 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004432 zero = makeSmearedConstant(zero, vectorSize);
4433 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4434
4435 case glslang::EOpConvFloatToBool:
4436 zero = builder.makeFloatConstant(0.0F);
4437 zero = makeSmearedConstant(zero, vectorSize);
4438 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4439
4440 case glslang::EOpConvDoubleToBool:
4441 zero = builder.makeDoubleConstant(0.0);
4442 zero = makeSmearedConstant(zero, vectorSize);
4443 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4444
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004445#ifdef AMD_EXTENSIONS
4446 case glslang::EOpConvFloat16ToBool:
4447 zero = builder.makeFloat16Constant(0.0F);
4448 zero = makeSmearedConstant(zero, vectorSize);
4449 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4450#endif
4451
John Kessenich140f3df2015-06-26 16:58:36 -06004452 case glslang::EOpConvBoolToFloat:
4453 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004454 zero = builder.makeFloatConstant(0.0F);
4455 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004456 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004457
John Kessenich140f3df2015-06-26 16:58:36 -06004458 case glslang::EOpConvBoolToDouble:
4459 convOp = spv::OpSelect;
4460 zero = builder.makeDoubleConstant(0.0);
4461 one = builder.makeDoubleConstant(1.0);
4462 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004463
4464#ifdef AMD_EXTENSIONS
4465 case glslang::EOpConvBoolToFloat16:
4466 convOp = spv::OpSelect;
4467 zero = builder.makeFloat16Constant(0.0F);
4468 one = builder.makeFloat16Constant(1.0F);
4469 break;
4470#endif
4471
John Kessenich140f3df2015-06-26 16:58:36 -06004472 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004473 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004474#ifdef AMD_EXTENSIONS
4475 case glslang::EOpConvBoolToInt16:
4476#endif
4477 if (op == glslang::EOpConvBoolToInt64)
4478 zero = builder.makeInt64Constant(0);
4479#ifdef AMD_EXTENSIONS
4480 else if (op == glslang::EOpConvBoolToInt16)
4481 zero = builder.makeInt16Constant(0);
4482#endif
4483 else
4484 zero = builder.makeIntConstant(0);
4485
4486 if (op == glslang::EOpConvBoolToInt64)
4487 one = builder.makeInt64Constant(1);
4488#ifdef AMD_EXTENSIONS
4489 else if (op == glslang::EOpConvBoolToInt16)
4490 one = builder.makeInt16Constant(1);
4491#endif
4492 else
4493 one = builder.makeIntConstant(1);
4494
John Kessenich140f3df2015-06-26 16:58:36 -06004495 convOp = spv::OpSelect;
4496 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004497
John Kessenich140f3df2015-06-26 16:58:36 -06004498 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004499 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004500#ifdef AMD_EXTENSIONS
4501 case glslang::EOpConvBoolToUint16:
4502#endif
4503 if (op == glslang::EOpConvBoolToUint64)
4504 zero = builder.makeUint64Constant(0);
4505#ifdef AMD_EXTENSIONS
4506 else if (op == glslang::EOpConvBoolToUint16)
4507 zero = builder.makeUint16Constant(0);
4508#endif
4509 else
4510 zero = builder.makeUintConstant(0);
4511
4512 if (op == glslang::EOpConvBoolToUint64)
4513 one = builder.makeUint64Constant(1);
4514#ifdef AMD_EXTENSIONS
4515 else if (op == glslang::EOpConvBoolToUint16)
4516 one = builder.makeUint16Constant(1);
4517#endif
4518 else
4519 one = builder.makeUintConstant(1);
4520
John Kessenich140f3df2015-06-26 16:58:36 -06004521 convOp = spv::OpSelect;
4522 break;
4523
4524 case glslang::EOpConvIntToFloat:
4525 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004526 case glslang::EOpConvInt64ToFloat:
4527 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004528#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004529 case glslang::EOpConvInt16ToFloat:
4530 case glslang::EOpConvInt16ToDouble:
4531 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004532 case glslang::EOpConvIntToFloat16:
4533 case glslang::EOpConvInt64ToFloat16:
4534#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004535 convOp = spv::OpConvertSToF;
4536 break;
4537
4538 case glslang::EOpConvUintToFloat:
4539 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004540 case glslang::EOpConvUint64ToFloat:
4541 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004542#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004543 case glslang::EOpConvUint16ToFloat:
4544 case glslang::EOpConvUint16ToDouble:
4545 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004546 case glslang::EOpConvUintToFloat16:
4547 case glslang::EOpConvUint64ToFloat16:
4548#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004549 convOp = spv::OpConvertUToF;
4550 break;
4551
4552 case glslang::EOpConvDoubleToFloat:
4553 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004554#ifdef AMD_EXTENSIONS
4555 case glslang::EOpConvDoubleToFloat16:
4556 case glslang::EOpConvFloat16ToDouble:
4557 case glslang::EOpConvFloatToFloat16:
4558 case glslang::EOpConvFloat16ToFloat:
4559#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004560 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004561 if (builder.isMatrixType(destType))
4562 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004563 break;
4564
4565 case glslang::EOpConvFloatToInt:
4566 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004567 case glslang::EOpConvFloatToInt64:
4568 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004569#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004570 case glslang::EOpConvFloatToInt16:
4571 case glslang::EOpConvDoubleToInt16:
4572 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004573 case glslang::EOpConvFloat16ToInt:
4574 case glslang::EOpConvFloat16ToInt64:
4575#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004576 convOp = spv::OpConvertFToS;
4577 break;
4578
4579 case glslang::EOpConvUintToInt:
4580 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004581 case glslang::EOpConvUint64ToInt64:
4582 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004583#ifdef AMD_EXTENSIONS
4584 case glslang::EOpConvUint16ToInt16:
4585 case glslang::EOpConvInt16ToUint16:
4586#endif
qininge24aa5e2016-04-07 15:40:27 -04004587 if (builder.isInSpecConstCodeGenMode()) {
4588 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004589 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4590 zero = builder.makeUint64Constant(0);
4591#ifdef AMD_EXTENSIONS
4592 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4593 zero = builder.makeUint16Constant(0);
4594#endif
4595 else
4596 zero = builder.makeUintConstant(0);
4597
qining189b2032016-04-12 23:16:20 -04004598 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004599 // Use OpIAdd, instead of OpBitcast to do the conversion when
4600 // generating for OpSpecConstantOp instruction.
4601 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4602 }
4603 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004604 convOp = spv::OpBitcast;
4605 break;
4606
4607 case glslang::EOpConvFloatToUint:
4608 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004609 case glslang::EOpConvFloatToUint64:
4610 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004611#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004612 case glslang::EOpConvFloatToUint16:
4613 case glslang::EOpConvDoubleToUint16:
4614 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004615 case glslang::EOpConvFloat16ToUint:
4616 case glslang::EOpConvFloat16ToUint64:
4617#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004618 convOp = spv::OpConvertFToU;
4619 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004620
4621 case glslang::EOpConvIntToInt64:
4622 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004623#ifdef AMD_EXTENSIONS
4624 case glslang::EOpConvIntToInt16:
4625 case glslang::EOpConvInt16ToInt:
4626 case glslang::EOpConvInt64ToInt16:
4627 case glslang::EOpConvInt16ToInt64:
4628#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004629 convOp = spv::OpSConvert;
4630 break;
4631
4632 case glslang::EOpConvUintToUint64:
4633 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004634#ifdef AMD_EXTENSIONS
4635 case glslang::EOpConvUintToUint16:
4636 case glslang::EOpConvUint16ToUint:
4637 case glslang::EOpConvUint64ToUint16:
4638 case glslang::EOpConvUint16ToUint64:
4639#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004640 convOp = spv::OpUConvert;
4641 break;
4642
4643 case glslang::EOpConvIntToUint64:
4644 case glslang::EOpConvInt64ToUint:
4645 case glslang::EOpConvUint64ToInt:
4646 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004647#ifdef AMD_EXTENSIONS
4648 case glslang::EOpConvInt16ToUint:
4649 case glslang::EOpConvUintToInt16:
4650 case glslang::EOpConvInt16ToUint64:
4651 case glslang::EOpConvUint64ToInt16:
4652 case glslang::EOpConvUint16ToInt:
4653 case glslang::EOpConvIntToUint16:
4654 case glslang::EOpConvUint16ToInt64:
4655 case glslang::EOpConvInt64ToUint16:
4656#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004657 // OpSConvert/OpUConvert + OpBitCast
4658 switch (op) {
4659 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004660#ifdef AMD_EXTENSIONS
4661 case glslang::EOpConvInt16ToUint64:
4662#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004663 convOp = spv::OpSConvert;
4664 type = builder.makeIntType(64);
4665 break;
4666 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004667#ifdef AMD_EXTENSIONS
4668 case glslang::EOpConvInt16ToUint:
4669#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004670 convOp = spv::OpSConvert;
4671 type = builder.makeIntType(32);
4672 break;
4673 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004674#ifdef AMD_EXTENSIONS
4675 case glslang::EOpConvUint16ToInt:
4676#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004677 convOp = spv::OpUConvert;
4678 type = builder.makeUintType(32);
4679 break;
4680 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004681#ifdef AMD_EXTENSIONS
4682 case glslang::EOpConvUint16ToInt64:
4683#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004684 convOp = spv::OpUConvert;
4685 type = builder.makeUintType(64);
4686 break;
Rex Xucabbb782017-03-24 13:41:14 +08004687#ifdef AMD_EXTENSIONS
4688 case glslang::EOpConvUintToInt16:
4689 case glslang::EOpConvUint64ToInt16:
4690 convOp = spv::OpUConvert;
4691 type = builder.makeUintType(16);
4692 break;
4693 case glslang::EOpConvIntToUint16:
4694 case glslang::EOpConvInt64ToUint16:
4695 convOp = spv::OpSConvert;
4696 type = builder.makeIntType(16);
4697 break;
4698#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004699 default:
4700 assert(0);
4701 break;
4702 }
4703
4704 if (vectorSize > 0)
4705 type = builder.makeVectorType(type, vectorSize);
4706
4707 operand = builder.createUnaryOp(convOp, type, operand);
4708
4709 if (builder.isInSpecConstCodeGenMode()) {
4710 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004711#ifdef AMD_EXTENSIONS
4712 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4713 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4714 zero = builder.makeUint64Constant(0);
4715 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4716 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4717 zero = builder.makeUint16Constant(0);
4718 else
4719 zero = builder.makeUintConstant(0);
4720#else
4721 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4722 zero = builder.makeUint64Constant(0);
4723 else
4724 zero = builder.makeUintConstant(0);
4725#endif
4726
Rex Xu8ff43de2016-04-22 16:51:45 +08004727 zero = makeSmearedConstant(zero, vectorSize);
4728 // Use OpIAdd, instead of OpBitcast to do the conversion when
4729 // generating for OpSpecConstantOp instruction.
4730 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4731 }
4732 // For normal run-time conversion instruction, use OpBitcast.
4733 convOp = spv::OpBitcast;
4734 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004735 default:
4736 break;
4737 }
4738
4739 spv::Id result = 0;
4740 if (convOp == spv::OpNop)
4741 return result;
4742
4743 if (convOp == spv::OpSelect) {
4744 zero = makeSmearedConstant(zero, vectorSize);
4745 one = makeSmearedConstant(one, vectorSize);
4746 result = builder.createTriOp(convOp, destType, operand, one, zero);
4747 } else
4748 result = builder.createUnaryOp(convOp, destType, operand);
4749
John Kessenich32cfd492016-02-02 12:37:46 -07004750 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004751}
4752
4753spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4754{
4755 if (vectorSize == 0)
4756 return constant;
4757
4758 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4759 std::vector<spv::Id> components;
4760 for (int c = 0; c < vectorSize; ++c)
4761 components.push_back(constant);
4762 return builder.makeCompositeConstant(vectorTypeId, components);
4763}
4764
John Kessenich426394d2015-07-23 10:22:48 -06004765// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004766spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich426394d2015-07-23 10:22:48 -06004767{
4768 spv::Op opCode = spv::OpNop;
4769
4770 switch (op) {
4771 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004772 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004773 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004774 opCode = spv::OpAtomicIAdd;
4775 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004776 case glslang::EOpAtomicCounterSubtract:
4777 opCode = spv::OpAtomicISub;
4778 break;
John Kessenich426394d2015-07-23 10:22:48 -06004779 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004780 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004781 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08004782 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004783 break;
4784 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004785 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004786 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08004787 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004788 break;
4789 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004790 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004791 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004792 opCode = spv::OpAtomicAnd;
4793 break;
4794 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004795 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004796 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004797 opCode = spv::OpAtomicOr;
4798 break;
4799 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004800 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004801 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004802 opCode = spv::OpAtomicXor;
4803 break;
4804 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004805 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004806 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004807 opCode = spv::OpAtomicExchange;
4808 break;
4809 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004810 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004811 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004812 opCode = spv::OpAtomicCompareExchange;
4813 break;
4814 case glslang::EOpAtomicCounterIncrement:
4815 opCode = spv::OpAtomicIIncrement;
4816 break;
4817 case glslang::EOpAtomicCounterDecrement:
4818 opCode = spv::OpAtomicIDecrement;
4819 break;
4820 case glslang::EOpAtomicCounter:
4821 opCode = spv::OpAtomicLoad;
4822 break;
4823 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004824 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004825 break;
4826 }
4827
Rex Xue8fe8b02017-09-26 15:42:56 +08004828 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
4829 builder.addCapability(spv::CapabilityInt64Atomics);
4830
John Kessenich426394d2015-07-23 10:22:48 -06004831 // Sort out the operands
4832 // - mapping from glslang -> SPV
4833 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004834 // - compare-exchange swaps the value and comparator
4835 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004836 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4837 auto opIt = operands.begin(); // walk the glslang operands
4838 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004839 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4840 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4841 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004842 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4843 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004844 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004845 spvAtomicOperands.push_back(*(opIt + 1));
4846 spvAtomicOperands.push_back(*opIt);
4847 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004848 }
John Kessenich426394d2015-07-23 10:22:48 -06004849
John Kessenich3e60a6f2015-09-14 22:45:16 -06004850 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004851 for (; opIt != operands.end(); ++opIt)
4852 spvAtomicOperands.push_back(*opIt);
4853
4854 return builder.createOp(opCode, typeId, spvAtomicOperands);
4855}
4856
John Kessenich91cef522016-05-05 16:45:40 -06004857// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004858spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004859{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004860#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004861 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004862 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004863#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004864
Rex Xu51596642016-09-21 18:56:12 +08004865 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004866 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004867 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4868
chaocf200da82016-12-20 12:44:35 -08004869 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4870 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004871 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4872 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004873 } else if (op == glslang::EOpAnyInvocation ||
4874 op == glslang::EOpAllInvocations ||
4875 op == glslang::EOpAllInvocationsEqual) {
4876 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4877 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004878 } else {
4879 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004880#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004881 if (op == glslang::EOpMinInvocationsNonUniform ||
4882 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004883 op == glslang::EOpAddInvocationsNonUniform ||
4884 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4885 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4886 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4887 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4888 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4889 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004890 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004891#endif
Rex Xu51596642016-09-21 18:56:12 +08004892
4893 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004894#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004895 switch (op) {
4896 case glslang::EOpMinInvocations:
4897 case glslang::EOpMaxInvocations:
4898 case glslang::EOpAddInvocations:
4899 case glslang::EOpMinInvocationsNonUniform:
4900 case glslang::EOpMaxInvocationsNonUniform:
4901 case glslang::EOpAddInvocationsNonUniform:
4902 groupOperation = spv::GroupOperationReduce;
4903 spvGroupOperands.push_back(groupOperation);
4904 break;
4905 case glslang::EOpMinInvocationsInclusiveScan:
4906 case glslang::EOpMaxInvocationsInclusiveScan:
4907 case glslang::EOpAddInvocationsInclusiveScan:
4908 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4909 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4910 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4911 groupOperation = spv::GroupOperationInclusiveScan;
4912 spvGroupOperands.push_back(groupOperation);
4913 break;
4914 case glslang::EOpMinInvocationsExclusiveScan:
4915 case glslang::EOpMaxInvocationsExclusiveScan:
4916 case glslang::EOpAddInvocationsExclusiveScan:
4917 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4918 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4919 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4920 groupOperation = spv::GroupOperationExclusiveScan;
4921 spvGroupOperands.push_back(groupOperation);
4922 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004923 default:
4924 break;
Rex Xu430ef402016-10-14 17:22:23 +08004925 }
Rex Xu9d93a232016-05-05 12:30:44 +08004926#endif
Rex Xu51596642016-09-21 18:56:12 +08004927 }
4928
4929 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4930 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004931
4932 switch (op) {
4933 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004934 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004935 break;
John Kessenich91cef522016-05-05 16:45:40 -06004936 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004937 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004938 break;
John Kessenich91cef522016-05-05 16:45:40 -06004939 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004940 opCode = spv::OpSubgroupAllEqualKHR;
4941 break;
Rex Xu51596642016-09-21 18:56:12 +08004942 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004943 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004944 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004945 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004946 break;
4947 case glslang::EOpReadFirstInvocation:
4948 opCode = spv::OpSubgroupFirstInvocationKHR;
4949 break;
4950 case glslang::EOpBallot:
4951 {
4952 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4953 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4954 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4955 //
4956 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4957 //
4958 spv::Id uintType = builder.makeUintType(32);
4959 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4960 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4961
4962 std::vector<spv::Id> components;
4963 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4964 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4965
4966 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4967 return builder.createUnaryOp(spv::OpBitcast, typeId,
4968 builder.createCompositeConstruct(uvec2Type, components));
4969 }
4970
Rex Xu9d93a232016-05-05 12:30:44 +08004971#ifdef AMD_EXTENSIONS
4972 case glslang::EOpMinInvocations:
4973 case glslang::EOpMaxInvocations:
4974 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004975 case glslang::EOpMinInvocationsInclusiveScan:
4976 case glslang::EOpMaxInvocationsInclusiveScan:
4977 case glslang::EOpAddInvocationsInclusiveScan:
4978 case glslang::EOpMinInvocationsExclusiveScan:
4979 case glslang::EOpMaxInvocationsExclusiveScan:
4980 case glslang::EOpAddInvocationsExclusiveScan:
4981 if (op == glslang::EOpMinInvocations ||
4982 op == glslang::EOpMinInvocationsInclusiveScan ||
4983 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004984 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004985 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004986 else {
4987 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004988 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004989 else
Rex Xu51596642016-09-21 18:56:12 +08004990 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004991 }
Rex Xu430ef402016-10-14 17:22:23 +08004992 } else if (op == glslang::EOpMaxInvocations ||
4993 op == glslang::EOpMaxInvocationsInclusiveScan ||
4994 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004995 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004996 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004997 else {
4998 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004999 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005000 else
Rex Xu51596642016-09-21 18:56:12 +08005001 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005002 }
5003 } else {
5004 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005005 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005006 else
Rex Xu51596642016-09-21 18:56:12 +08005007 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005008 }
5009
Rex Xu2bbbe062016-08-23 15:41:05 +08005010 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005011 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005012
5013 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005014 case glslang::EOpMinInvocationsNonUniform:
5015 case glslang::EOpMaxInvocationsNonUniform:
5016 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005017 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5018 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5019 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5020 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5021 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5022 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5023 if (op == glslang::EOpMinInvocationsNonUniform ||
5024 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5025 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005026 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005027 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005028 else {
5029 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005030 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005031 else
Rex Xu51596642016-09-21 18:56:12 +08005032 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005033 }
5034 }
Rex Xu430ef402016-10-14 17:22:23 +08005035 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5036 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5037 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005038 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005039 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005040 else {
5041 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005042 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005043 else
Rex Xu51596642016-09-21 18:56:12 +08005044 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005045 }
5046 }
5047 else {
5048 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005049 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005050 else
Rex Xu51596642016-09-21 18:56:12 +08005051 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005052 }
5053
Rex Xu2bbbe062016-08-23 15:41:05 +08005054 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005055 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005056
5057 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005058#endif
John Kessenich91cef522016-05-05 16:45:40 -06005059 default:
5060 logger->missingFunctionality("invocation operation");
5061 return spv::NoResult;
5062 }
Rex Xu51596642016-09-21 18:56:12 +08005063
5064 assert(opCode != spv::OpNop);
5065 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005066}
5067
Rex Xu2bbbe062016-08-23 15:41:05 +08005068// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005069spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005070{
Rex Xub7072052016-09-26 15:53:40 +08005071#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005072 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5073 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005074 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005075 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005076 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5077 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5078 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005079#else
5080 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5081 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005082 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5083 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005084#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005085
5086 // Handle group invocation operations scalar by scalar.
5087 // The result type is the same type as the original type.
5088 // The algorithm is to:
5089 // - break the vector into scalars
5090 // - apply the operation to each scalar
5091 // - make a vector out the scalar results
5092
5093 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005094 int numComponents = builder.getNumComponents(operands[0]);
5095 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005096 std::vector<spv::Id> results;
5097
5098 // do each scalar op
5099 for (int comp = 0; comp < numComponents; ++comp) {
5100 std::vector<unsigned int> indexes;
5101 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005102 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005103 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005104 if (op == spv::OpSubgroupReadInvocationKHR) {
5105 spvGroupOperands.push_back(scalar);
5106 spvGroupOperands.push_back(operands[1]);
5107 } else if (op == spv::OpGroupBroadcast) {
5108 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005109 spvGroupOperands.push_back(scalar);
5110 spvGroupOperands.push_back(operands[1]);
5111 } else {
chaocf200da82016-12-20 12:44:35 -08005112 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005113 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005114 spvGroupOperands.push_back(scalar);
5115 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005116
Rex Xub7072052016-09-26 15:53:40 +08005117 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005118 }
5119
5120 // put the pieces together
5121 return builder.createCompositeConstruct(typeId, results);
5122}
Rex Xu2bbbe062016-08-23 15:41:05 +08005123
John Kessenich5e4b1242015-08-06 22:53:06 -06005124spv::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 -06005125{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005126#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005127 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005128 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5129#else
Rex Xucabbb782017-03-24 13:41:14 +08005130 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005131 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005132#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005133
John Kessenich140f3df2015-06-26 16:58:36 -06005134 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005135 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005136 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005137 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005138 spv::Id typeId0 = 0;
5139 if (consumedOperands > 0)
5140 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005141 spv::Id typeId1 = 0;
5142 if (consumedOperands > 1)
5143 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005144 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005145
5146 switch (op) {
5147 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005148 if (isFloat)
5149 libCall = spv::GLSLstd450FMin;
5150 else if (isUnsigned)
5151 libCall = spv::GLSLstd450UMin;
5152 else
5153 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005154 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005155 break;
5156 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005157 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005158 break;
5159 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005160 if (isFloat)
5161 libCall = spv::GLSLstd450FMax;
5162 else if (isUnsigned)
5163 libCall = spv::GLSLstd450UMax;
5164 else
5165 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005166 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005167 break;
5168 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005169 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005170 break;
5171 case glslang::EOpDot:
5172 opCode = spv::OpDot;
5173 break;
5174 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005175 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005176 break;
5177
5178 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005179 if (isFloat)
5180 libCall = spv::GLSLstd450FClamp;
5181 else if (isUnsigned)
5182 libCall = spv::GLSLstd450UClamp;
5183 else
5184 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005185 builder.promoteScalar(precision, operands.front(), operands[1]);
5186 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005187 break;
5188 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005189 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5190 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005191 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005192 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005193 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005194 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005195 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005196 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005197 break;
5198 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005199 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005200 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005201 break;
5202 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005203 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005204 builder.promoteScalar(precision, operands[0], operands[2]);
5205 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005206 break;
5207
5208 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005209 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005210 break;
5211 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005212 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005213 break;
5214 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005215 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005216 break;
5217 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005218 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005219 break;
5220 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005221 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005222 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005223 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005224 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005225 libCall = spv::GLSLstd450InterpolateAtSample;
5226 break;
5227 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005228 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005229 libCall = spv::GLSLstd450InterpolateAtOffset;
5230 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005231 case glslang::EOpAddCarry:
5232 opCode = spv::OpIAddCarry;
5233 typeId = builder.makeStructResultType(typeId0, typeId0);
5234 consumedOperands = 2;
5235 break;
5236 case glslang::EOpSubBorrow:
5237 opCode = spv::OpISubBorrow;
5238 typeId = builder.makeStructResultType(typeId0, typeId0);
5239 consumedOperands = 2;
5240 break;
5241 case glslang::EOpUMulExtended:
5242 opCode = spv::OpUMulExtended;
5243 typeId = builder.makeStructResultType(typeId0, typeId0);
5244 consumedOperands = 2;
5245 break;
5246 case glslang::EOpIMulExtended:
5247 opCode = spv::OpSMulExtended;
5248 typeId = builder.makeStructResultType(typeId0, typeId0);
5249 consumedOperands = 2;
5250 break;
5251 case glslang::EOpBitfieldExtract:
5252 if (isUnsigned)
5253 opCode = spv::OpBitFieldUExtract;
5254 else
5255 opCode = spv::OpBitFieldSExtract;
5256 break;
5257 case glslang::EOpBitfieldInsert:
5258 opCode = spv::OpBitFieldInsert;
5259 break;
5260
5261 case glslang::EOpFma:
5262 libCall = spv::GLSLstd450Fma;
5263 break;
5264 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005265 {
5266 libCall = spv::GLSLstd450FrexpStruct;
5267 assert(builder.isPointerType(typeId1));
5268 typeId1 = builder.getContainedTypeId(typeId1);
5269#ifdef AMD_EXTENSIONS
5270 int width = builder.getScalarTypeWidth(typeId1);
5271#else
5272 int width = 32;
5273#endif
5274 if (builder.getNumComponents(operands[0]) == 1)
5275 frexpIntType = builder.makeIntegerType(width, true);
5276 else
5277 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5278 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5279 consumedOperands = 1;
5280 }
John Kessenich55e7d112015-11-15 21:33:39 -07005281 break;
5282 case glslang::EOpLdexp:
5283 libCall = spv::GLSLstd450Ldexp;
5284 break;
5285
Rex Xu574ab042016-04-14 16:53:07 +08005286 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005287 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005288
Rex Xu9d93a232016-05-05 12:30:44 +08005289#ifdef AMD_EXTENSIONS
5290 case glslang::EOpSwizzleInvocations:
5291 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5292 libCall = spv::SwizzleInvocationsAMD;
5293 break;
5294 case glslang::EOpSwizzleInvocationsMasked:
5295 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5296 libCall = spv::SwizzleInvocationsMaskedAMD;
5297 break;
5298 case glslang::EOpWriteInvocation:
5299 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5300 libCall = spv::WriteInvocationAMD;
5301 break;
5302
5303 case glslang::EOpMin3:
5304 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5305 if (isFloat)
5306 libCall = spv::FMin3AMD;
5307 else {
5308 if (isUnsigned)
5309 libCall = spv::UMin3AMD;
5310 else
5311 libCall = spv::SMin3AMD;
5312 }
5313 break;
5314 case glslang::EOpMax3:
5315 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5316 if (isFloat)
5317 libCall = spv::FMax3AMD;
5318 else {
5319 if (isUnsigned)
5320 libCall = spv::UMax3AMD;
5321 else
5322 libCall = spv::SMax3AMD;
5323 }
5324 break;
5325 case glslang::EOpMid3:
5326 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5327 if (isFloat)
5328 libCall = spv::FMid3AMD;
5329 else {
5330 if (isUnsigned)
5331 libCall = spv::UMid3AMD;
5332 else
5333 libCall = spv::SMid3AMD;
5334 }
5335 break;
5336
5337 case glslang::EOpInterpolateAtVertex:
5338 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5339 libCall = spv::InterpolateAtVertexAMD;
5340 break;
5341#endif
5342
John Kessenich140f3df2015-06-26 16:58:36 -06005343 default:
5344 return 0;
5345 }
5346
5347 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005348 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005349 // Use an extended instruction from the standard library.
5350 // Construct the call arguments, without modifying the original operands vector.
5351 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5352 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005353 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005354 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005355 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005356 case 0:
5357 // should all be handled by visitAggregate and createNoArgOperation
5358 assert(0);
5359 return 0;
5360 case 1:
5361 // should all be handled by createUnaryOperation
5362 assert(0);
5363 return 0;
5364 case 2:
5365 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5366 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005367 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005368 // anything 3 or over doesn't have l-value operands, so all should be consumed
5369 assert(consumedOperands == operands.size());
5370 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005371 break;
5372 }
5373 }
5374
John Kessenich55e7d112015-11-15 21:33:39 -07005375 // Decode the return types that were structures
5376 switch (op) {
5377 case glslang::EOpAddCarry:
5378 case glslang::EOpSubBorrow:
5379 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5380 id = builder.createCompositeExtract(id, typeId0, 0);
5381 break;
5382 case glslang::EOpUMulExtended:
5383 case glslang::EOpIMulExtended:
5384 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5385 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5386 break;
5387 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005388 {
5389 assert(operands.size() == 2);
5390 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5391 // "exp" is floating-point type (from HLSL intrinsic)
5392 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5393 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5394 builder.createStore(member1, operands[1]);
5395 } else
5396 // "exp" is integer type (from GLSL built-in function)
5397 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5398 id = builder.createCompositeExtract(id, typeId0, 0);
5399 }
John Kessenich55e7d112015-11-15 21:33:39 -07005400 break;
5401 default:
5402 break;
5403 }
5404
John Kessenich32cfd492016-02-02 12:37:46 -07005405 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005406}
5407
Rex Xu9d93a232016-05-05 12:30:44 +08005408// Intrinsics with no arguments (or no return value, and no precision).
5409spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005410{
5411 // TODO: get the barrier operands correct
5412
5413 switch (op) {
5414 case glslang::EOpEmitVertex:
5415 builder.createNoResultOp(spv::OpEmitVertex);
5416 return 0;
5417 case glslang::EOpEndPrimitive:
5418 builder.createNoResultOp(spv::OpEndPrimitive);
5419 return 0;
5420 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005421 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005422 return 0;
5423 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005424 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005425 return 0;
5426 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005427 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005428 return 0;
5429 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005430 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005431 return 0;
5432 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005433 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005434 return 0;
5435 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005436 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005437 return 0;
5438 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005439 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005440 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005441 case glslang::EOpAllMemoryBarrierWithGroupSync:
5442 // Control barrier with non-"None" semantic is also a memory barrier.
5443 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5444 return 0;
5445 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5446 // Control barrier with non-"None" semantic is also a memory barrier.
5447 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5448 return 0;
5449 case glslang::EOpWorkgroupMemoryBarrier:
5450 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5451 return 0;
5452 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5453 // Control barrier with non-"None" semantic is also a memory barrier.
5454 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5455 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005456#ifdef AMD_EXTENSIONS
5457 case glslang::EOpTime:
5458 {
5459 std::vector<spv::Id> args; // Dummy arguments
5460 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5461 return builder.setPrecision(id, precision);
5462 }
5463#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005464 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005465 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005466 return 0;
5467 }
5468}
5469
5470spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5471{
John Kessenich2f273362015-07-18 22:34:27 -06005472 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005473 spv::Id id;
5474 if (symbolValues.end() != iter) {
5475 id = iter->second;
5476 return id;
5477 }
5478
5479 // it was not found, create it
5480 id = createSpvVariable(symbol);
5481 symbolValues[symbol->getId()] = id;
5482
Rex Xuc884b4a2016-06-29 15:03:44 +08005483 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005484 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005485 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005486 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005487 if (symbol->getType().getQualifier().hasSpecConstantId())
5488 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005489 if (symbol->getQualifier().hasIndex())
5490 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5491 if (symbol->getQualifier().hasComponent())
5492 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5493 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005494 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005495 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005496 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005497 if (symbol->getQualifier().hasXfbBuffer())
5498 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5499 if (symbol->getQualifier().hasXfbOffset())
5500 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5501 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005502 // atomic counters use this:
5503 if (symbol->getQualifier().hasOffset())
5504 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005505 }
5506
scygan2c864272016-05-18 18:09:17 +02005507 if (symbol->getQualifier().hasLocation())
5508 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005509 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005510 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005511 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005512 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005513 }
John Kessenich140f3df2015-06-26 16:58:36 -06005514 if (symbol->getQualifier().hasSet())
5515 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005516 else if (IsDescriptorResource(symbol->getType())) {
5517 // default to 0
5518 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5519 }
John Kessenich140f3df2015-06-26 16:58:36 -06005520 if (symbol->getQualifier().hasBinding())
5521 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005522 if (symbol->getQualifier().hasAttachment())
5523 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005524 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005525 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005526 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005527 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005528 if (symbol->getQualifier().hasXfbBuffer())
5529 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5530 }
5531
Rex Xu1da878f2016-02-21 20:59:01 +08005532 if (symbol->getType().isImage()) {
5533 std::vector<spv::Decoration> memory;
5534 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5535 for (unsigned int i = 0; i < memory.size(); ++i)
5536 addDecoration(id, memory[i]);
5537 }
5538
John Kessenich140f3df2015-06-26 16:58:36 -06005539 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005540 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005541 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005542 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005543
John Kessenichecba76f2017-01-06 00:34:48 -07005544#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005545 if (builtIn == spv::BuiltInSampleMask) {
5546 spv::Decoration decoration;
5547 // GL_NV_sample_mask_override_coverage extension
5548 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005549 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005550 else
5551 decoration = (spv::Decoration)spv::DecorationMax;
5552 addDecoration(id, decoration);
5553 if (decoration != spv::DecorationMax) {
5554 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5555 }
5556 }
chaoc771d89f2017-01-13 01:10:53 -08005557 else if (builtIn == spv::BuiltInLayer) {
5558 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005559 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005560 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5561 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5562 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5563 }
John Kessenichb41bff62017-08-11 13:07:17 -06005564 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005565 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5566 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5567 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5568 }
5569 }
5570
chaoc6e5acae2016-12-20 13:28:52 -08005571 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005572 addDecoration(id, spv::DecorationPassthroughNV);
5573 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005574 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5575 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005576#endif
5577
John Kessenich140f3df2015-06-26 16:58:36 -06005578 return id;
5579}
5580
John Kessenich55e7d112015-11-15 21:33:39 -07005581// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005582void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5583{
John Kessenich4016e382016-07-15 11:53:56 -06005584 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005585 builder.addDecoration(id, dec);
5586}
5587
John Kessenich55e7d112015-11-15 21:33:39 -07005588// If 'dec' is valid, add a one-operand decoration to an object
5589void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5590{
John Kessenich4016e382016-07-15 11:53:56 -06005591 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005592 builder.addDecoration(id, dec, value);
5593}
5594
5595// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005596void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5597{
John Kessenich4016e382016-07-15 11:53:56 -06005598 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005599 builder.addMemberDecoration(id, (unsigned)member, dec);
5600}
5601
John Kessenich92187592016-02-01 13:45:25 -07005602// If 'dec' is valid, add a one-operand decoration to a struct member
5603void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5604{
John Kessenich4016e382016-07-15 11:53:56 -06005605 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005606 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5607}
5608
John Kessenich55e7d112015-11-15 21:33:39 -07005609// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005610// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005611//
5612// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5613//
5614// Recursively walk the nodes. The nodes form a tree whose leaves are
5615// regular constants, which themselves are trees that createSpvConstant()
5616// recursively walks. So, this function walks the "top" of the tree:
5617// - emit specialization constant-building instructions for specConstant
5618// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005619spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005620{
John Kessenich7cc0e282016-03-20 00:46:02 -06005621 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005622
qining4f4bb812016-04-03 23:55:17 -04005623 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005624 if (! node.getQualifier().specConstant) {
5625 // hand off to the non-spec-constant path
5626 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5627 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005628 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005629 nextConst, false);
5630 }
5631
5632 // We now know we have a specialization constant to build
5633
John Kessenichd94c0032016-05-30 19:29:40 -06005634 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005635 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5636 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5637 std::vector<spv::Id> dimConstId;
5638 for (int dim = 0; dim < 3; ++dim) {
5639 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5640 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5641 if (specConst)
5642 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5643 }
5644 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5645 }
5646
5647 // An AST node labelled as specialization constant should be a symbol node.
5648 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5649 if (auto* sn = node.getAsSymbolNode()) {
5650 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005651 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5652 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5653 // will set the builder into spec constant op instruction generating mode.
5654 sub_tree->traverse(this);
5655 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005656 } else if (auto* const_union_array = &sn->getConstArray()){
5657 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005658 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5659 builder.addName(id, sn->getName().c_str());
5660 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005661 }
5662 }
qining4f4bb812016-04-03 23:55:17 -04005663
5664 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5665 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005666 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005667 exit(1);
5668 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005669}
5670
John Kessenich140f3df2015-06-26 16:58:36 -06005671// Use 'consts' as the flattened glslang source of scalar constants to recursively
5672// build the aggregate SPIR-V constant.
5673//
5674// If there are not enough elements present in 'consts', 0 will be substituted;
5675// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5676//
qining08408382016-03-21 09:51:37 -04005677spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005678{
5679 // vector of constants for SPIR-V
5680 std::vector<spv::Id> spvConsts;
5681
5682 // Type is used for struct and array constants
5683 spv::Id typeId = convertGlslangToSpvType(glslangType);
5684
5685 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005686 glslang::TType elementType(glslangType, 0);
5687 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005688 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005689 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005690 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005691 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005692 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005693 } else if (glslangType.getStruct()) {
5694 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5695 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005696 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005697 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005698 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5699 bool zero = nextConst >= consts.size();
5700 switch (glslangType.getBasicType()) {
5701 case glslang::EbtInt:
5702 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5703 break;
5704 case glslang::EbtUint:
5705 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5706 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005707 case glslang::EbtInt64:
5708 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5709 break;
5710 case glslang::EbtUint64:
5711 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5712 break;
Rex Xucabbb782017-03-24 13:41:14 +08005713#ifdef AMD_EXTENSIONS
5714 case glslang::EbtInt16:
5715 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5716 break;
5717 case glslang::EbtUint16:
5718 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5719 break;
5720#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005721 case glslang::EbtFloat:
5722 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5723 break;
5724 case glslang::EbtDouble:
5725 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5726 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005727#ifdef AMD_EXTENSIONS
5728 case glslang::EbtFloat16:
5729 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5730 break;
5731#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005732 case glslang::EbtBool:
5733 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5734 break;
5735 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005736 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005737 break;
5738 }
5739 ++nextConst;
5740 }
5741 } else {
5742 // we have a non-aggregate (scalar) constant
5743 bool zero = nextConst >= consts.size();
5744 spv::Id scalar = 0;
5745 switch (glslangType.getBasicType()) {
5746 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005747 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005748 break;
5749 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005750 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005751 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005752 case glslang::EbtInt64:
5753 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5754 break;
5755 case glslang::EbtUint64:
5756 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5757 break;
Rex Xucabbb782017-03-24 13:41:14 +08005758#ifdef AMD_EXTENSIONS
5759 case glslang::EbtInt16:
5760 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5761 break;
5762 case glslang::EbtUint16:
5763 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5764 break;
5765#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005766 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005767 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005768 break;
5769 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005770 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005771 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005772#ifdef AMD_EXTENSIONS
5773 case glslang::EbtFloat16:
5774 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5775 break;
5776#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005777 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005778 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005779 break;
5780 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005781 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005782 break;
5783 }
5784 ++nextConst;
5785 return scalar;
5786 }
5787
5788 return builder.makeCompositeConstant(typeId, spvConsts);
5789}
5790
John Kessenich7c1aa102015-10-15 13:29:11 -06005791// Return true if the node is a constant or symbol whose reading has no
5792// non-trivial observable cost or effect.
5793bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5794{
5795 // don't know what this is
5796 if (node == nullptr)
5797 return false;
5798
5799 // a constant is safe
5800 if (node->getAsConstantUnion() != nullptr)
5801 return true;
5802
5803 // not a symbol means non-trivial
5804 if (node->getAsSymbolNode() == nullptr)
5805 return false;
5806
5807 // a symbol, depends on what's being read
5808 switch (node->getType().getQualifier().storage) {
5809 case glslang::EvqTemporary:
5810 case glslang::EvqGlobal:
5811 case glslang::EvqIn:
5812 case glslang::EvqInOut:
5813 case glslang::EvqConst:
5814 case glslang::EvqConstReadOnly:
5815 case glslang::EvqUniform:
5816 return true;
5817 default:
5818 return false;
5819 }
qining25262b32016-05-06 17:25:16 -04005820}
John Kessenich7c1aa102015-10-15 13:29:11 -06005821
5822// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005823// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005824// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005825// Return true if trivial.
5826bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5827{
5828 if (node == nullptr)
5829 return false;
5830
John Kessenich84cc15f2017-05-24 16:44:47 -06005831 // count non scalars as trivial, as well as anything coming from HLSL
5832 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005833 return true;
5834
John Kessenich7c1aa102015-10-15 13:29:11 -06005835 // symbols and constants are trivial
5836 if (isTrivialLeaf(node))
5837 return true;
5838
5839 // otherwise, it needs to be a simple operation or one or two leaf nodes
5840
5841 // not a simple operation
5842 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5843 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5844 if (binaryNode == nullptr && unaryNode == nullptr)
5845 return false;
5846
5847 // not on leaf nodes
5848 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5849 return false;
5850
5851 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5852 return false;
5853 }
5854
5855 switch (node->getAsOperator()->getOp()) {
5856 case glslang::EOpLogicalNot:
5857 case glslang::EOpConvIntToBool:
5858 case glslang::EOpConvUintToBool:
5859 case glslang::EOpConvFloatToBool:
5860 case glslang::EOpConvDoubleToBool:
5861 case glslang::EOpEqual:
5862 case glslang::EOpNotEqual:
5863 case glslang::EOpLessThan:
5864 case glslang::EOpGreaterThan:
5865 case glslang::EOpLessThanEqual:
5866 case glslang::EOpGreaterThanEqual:
5867 case glslang::EOpIndexDirect:
5868 case glslang::EOpIndexDirectStruct:
5869 case glslang::EOpLogicalXor:
5870 case glslang::EOpAny:
5871 case glslang::EOpAll:
5872 return true;
5873 default:
5874 return false;
5875 }
5876}
5877
5878// Emit short-circuiting code, where 'right' is never evaluated unless
5879// the left side is true (for &&) or false (for ||).
5880spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5881{
5882 spv::Id boolTypeId = builder.makeBoolType();
5883
5884 // emit left operand
5885 builder.clearAccessChain();
5886 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005887 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005888
5889 // Operands to accumulate OpPhi operands
5890 std::vector<spv::Id> phiOperands;
5891 // accumulate left operand's phi information
5892 phiOperands.push_back(leftId);
5893 phiOperands.push_back(builder.getBuildPoint()->getId());
5894
5895 // Make the two kinds of operation symmetric with a "!"
5896 // || => emit "if (! left) result = right"
5897 // && => emit "if ( left) result = right"
5898 //
5899 // TODO: this runtime "not" for || could be avoided by adding functionality
5900 // to 'builder' to have an "else" without an "then"
5901 if (op == glslang::EOpLogicalOr)
5902 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5903
5904 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005905 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005906
5907 // emit right operand as the "then" part of the "if"
5908 builder.clearAccessChain();
5909 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005910 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005911
5912 // accumulate left operand's phi information
5913 phiOperands.push_back(rightId);
5914 phiOperands.push_back(builder.getBuildPoint()->getId());
5915
5916 // finish the "if"
5917 ifBuilder.makeEndIf();
5918
5919 // phi together the two results
5920 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5921}
5922
Rex Xu9d93a232016-05-05 12:30:44 +08005923// Return type Id of the imported set of extended instructions corresponds to the name.
5924// Import this set if it has not been imported yet.
5925spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5926{
5927 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5928 return extBuiltinMap[name];
5929 else {
Rex Xu51596642016-09-21 18:56:12 +08005930 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005931 spv::Id extBuiltins = builder.import(name);
5932 extBuiltinMap[name] = extBuiltins;
5933 return extBuiltins;
5934 }
5935}
5936
John Kessenich140f3df2015-06-26 16:58:36 -06005937}; // end anonymous namespace
5938
5939namespace glslang {
5940
John Kessenich68d78fd2015-07-12 19:28:10 -06005941void GetSpirvVersion(std::string& version)
5942{
John Kessenich9e55f632015-07-15 10:03:39 -06005943 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005944 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005945 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005946 version = buf;
5947}
5948
John Kessenich140f3df2015-06-26 16:58:36 -06005949// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005950void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005951{
5952 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005953 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005954 if (out.fail())
5955 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005956 for (int i = 0; i < (int)spirv.size(); ++i) {
5957 unsigned int word = spirv[i];
5958 out.write((const char*)&word, 4);
5959 }
5960 out.close();
5961}
5962
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005963// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005964void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005965{
5966 std::ofstream out;
5967 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005968 if (out.fail())
5969 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005970 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005971 if (varName != nullptr) {
5972 out << "\t #pragma once" << std::endl;
5973 out << "const uint32_t " << varName << "[] = {" << std::endl;
5974 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005975 const int WORDS_PER_LINE = 8;
5976 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5977 out << "\t";
5978 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5979 const unsigned int word = spirv[i + j];
5980 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5981 if (i + j + 1 < (int)spirv.size()) {
5982 out << ",";
5983 }
5984 }
5985 out << std::endl;
5986 }
Flavio15017db2017-02-15 14:29:33 -08005987 if (varName != nullptr) {
5988 out << "};";
5989 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005990 out.close();
5991}
5992
GregFcd1f1692017-09-21 18:40:22 -06005993#ifdef ENABLE_OPT
5994void errHandler(const std::string& str) {
5995 std::cerr << str << std::endl;
5996}
5997#endif
5998
John Kessenich140f3df2015-06-26 16:58:36 -06005999//
6000// Set up the glslang traversal
6001//
John Kessenich121853f2017-05-31 17:11:16 -06006002void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006003{
Lei Zhang17535f72016-05-04 15:55:59 -04006004 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006005 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006006}
6007
John Kessenich121853f2017-05-31 17:11:16 -06006008void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6009 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006010{
John Kessenich140f3df2015-06-26 16:58:36 -06006011 TIntermNode* root = intermediate.getTreeRoot();
6012
6013 if (root == 0)
6014 return;
6015
John Kessenich121853f2017-05-31 17:11:16 -06006016 glslang::SpvOptions defaultOptions;
6017 if (options == nullptr)
6018 options = &defaultOptions;
6019
John Kessenich140f3df2015-06-26 16:58:36 -06006020 glslang::GetThreadPoolAllocator().push();
6021
John Kessenich121853f2017-05-31 17:11:16 -06006022 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006023 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006024 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006025 it.dumpSpv(spirv);
6026
GregFcd1f1692017-09-21 18:40:22 -06006027#ifdef ENABLE_OPT
6028 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6029 // eg. forward and remove memory writes of opaque types.
6030 if ((intermediate.getSource() == EShSourceHlsl ||
6031 options->optimizeSize) &&
6032 !options->disableOptimizer) {
6033 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6034
6035 spvtools::Optimizer optimizer(target_env);
6036 optimizer.SetMessageConsumer([](spv_message_level_t level,
6037 const char* source,
6038 const spv_position_t& position,
6039 const char* message) {
6040 std::cerr << StringifyMessage(level, source, position, message)
6041 << std::endl;
6042 });
6043
6044 optimizer.RegisterPass(CreateInlineExhaustivePass());
6045 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6046 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6047 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
6048 optimizer.RegisterPass(CreateInsertExtractElimPass());
6049 optimizer.RegisterPass(CreateAggressiveDCEPass());
6050 optimizer.RegisterPass(CreateDeadBranchElimPass());
6051 optimizer.RegisterPass(CreateBlockMergePass());
6052 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
6053 optimizer.RegisterPass(CreateInsertExtractElimPass());
6054 optimizer.RegisterPass(CreateAggressiveDCEPass());
6055 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6056 // if (options->optimizeSize)
6057 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6058
6059 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6060 return;
6061
6062 // Remove dead module-level objects: functions, types, vars
6063 // TODO(greg-lunarg): Switch to spirv-opt versions when available
6064 spv::spirvbin_t Remapper(0);
6065 Remapper.registerErrorHandler(errHandler);
6066 Remapper.remap(spirv, spv::spirvbin_t::DCE_ALL);
6067 }
6068#endif
6069
John Kessenich140f3df2015-06-26 16:58:36 -06006070 glslang::GetThreadPoolAllocator().pop();
6071}
6072
6073}; // end namespace glslang